C# 实战-三种类型的Timer

在C#中,主要有三种类型的Timer:

System.Windows.Forms.Timer

System.Timers.Timer

System.Threading.Timer

以下是每种Timer的简要说明和示例:

1. System.Windows.Forms.Timer

用于Windows Forms应用程序,适合在UI线程中使用。

csharp 复制代码
using System;
using System.Windows.Forms;

public class WinFormsTimerExample : Form
{
    private Timer timer;

    public WinFormsTimerExample()
    {
        timer = new Timer();
        timer.Interval = 1000; // 1秒
        timer.Tick += new EventHandler(OnTimerEvent);
        timer.Start();
    }

    private void OnTimerEvent(Object sender, EventArgs e)
    {
        Console.WriteLine("WinForms Timer ticked at: " + DateTime.Now);
    }

    [STAThread]
    public static void Main()
    {
        Application.Run(new WinFormsTimerExample());
    }

}

2. System.Timers.Timer

适用于需要更精确的计时和跨线程操作的场景。

csharp 复制代码
using System;
using System.Timers;

public class TimersTimerExample
{
    private static Timer timer;

    public static void Main()
    {
        timer = new Timer(1000); // 1秒
        timer.Elapsed += OnTimedEvent;
        timer.AutoReset = true;
        timer.Enabled = true;

        Console.WriteLine("Press Enter to exit the program...");
        Console.ReadLine();
    }

    private static void OnTimedEvent(Object source, ElapsedEventArgs e)
    {
        Console.WriteLine("Timers Timer ticked at: " + e.SignalTime);
    }
}

3. System.Threading.Timer

用于多线程环境,可以在任何线程上执行回调。

csharp 复制代码
using System;
using System.Threading;

public class ThreadingTimerExample
{
    private static Timer timer;

    public static void Main()
    {
        TimerCallback callback = new TimerCallback(OnTimerEvent);
        timer = new Timer(callback, null, 0, 1000); // 1秒

        Console.WriteLine("Press Enter to exit the program...");
        Console.ReadLine();
    }

    private static void OnTimerEvent(Object state)
    {
        Console.WriteLine("Threading Timer ticked at: " + DateTime.Now);
    }
}

通过这些示例,可以快速掌握每种Timer的使用场景和方法。

相关推荐
1-1=01 小时前
C# 委托与事件
开发语言·c#
Fuyo_11191 小时前
C++ 运行时多态与虚函数机制全面剖析【面试重点】
开发语言·c++·面试
w_zero_one2 小时前
递归算法(一)
java·开发语言·算法
Julien20043 小时前
管理机密(一)
运维·服务器·开发语言·学习方法
Chen_harmony3 小时前
七、STL与string类
开发语言·c++
沐晓时光3 小时前
C语言入门,字符串和字符串函数知识讲解
c语言·开发语言
xxxiugou1233 小时前
C++命名空间与引用全解析
开发语言·c++
yangmu32035 小时前
编程语言发展简史:从机器指令到智能协作
开发语言
Pniubi7 小时前
Java为什么要分堆和栈
java·开发语言
小小晓.8 小时前
Qt 对话框、QLineEdit 与布局管理实战详解
开发语言·qt