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的使用场景和方法。

相关推荐
551只玄猫5 分钟前
【数学建模 matlab 实验报告1】
开发语言·数学建模·matlab·课程设计·实验报告
三道渊1 小时前
C语言:文件I/O
c语言·开发语言·数据结构·c++
hnlgzb1 小时前
安卓app kotlin语法,Hilt是什么东西?
android·开发语言·kotlin
没用的阿_吉1 小时前
windows10 Qt5.15.14 msvc2019 编译部署
开发语言·qt
聊聊MES那点事1 小时前
JavaScript图表控件AG Charts使用教程:使用AG Charts React实时更新柱状图
开发语言·javascript·react.js·图表控件
ywf12151 小时前
Go基础之环境搭建
开发语言·后端·golang
是有头发的程序猿2 小时前
用Open Claw接口做1688选品、价格监控、货源对比
开发语言·c++·人工智能
斯班奇的好朋友阿法法2 小时前
离线ollama导入Qwen3.5-9B.Q8_0.gguf模型
开发语言·前端·javascript
计算机安禾2 小时前
【数据结构与算法】第19篇:树与二叉树的基础概念
c语言·开发语言·数据结构·c++·算法·visual studio code·visual studio
Zarek枫煜3 小时前
[特殊字符] C3语言:传承C之高效,突破C之局限
c语言·开发语言·c++·单片机·嵌入式硬件·物联网·算法