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

相关推荐
水云桐程序员3 小时前
C++可以写手机应用吗
开发语言·c++·智能手机
测试员周周3 小时前
【AI测试智能体】为什么传统测试方法对智能体失效?
开发语言·人工智能·python·功能测试·测试工具·单元测试·测试用例
RSTJ_16254 小时前
PYTHON+AI LLM DAY THREETY-NINE
开发语言·人工智能·python
火星papa4 小时前
C# 阻塞队列(BlockingCollection)
c#·queue·阻塞队列
赏金术士5 小时前
Kotlin 从入门到进阶 之函数模块(核心基础)(二)
android·开发语言·kotlin
加号37 小时前
【Qt】 应用程序发布:依赖库拷贝与部署指南
开发语言·qt
('-')7 小时前
八股复习2:Java Array list和Linked list
java·开发语言
小黄人软件7 小时前
C++读写编辑CSV文件示例源码 用于数据导入导出,比Excel好使
开发语言·c++·excel
郭涤生7 小时前
C++各个版本的性能和安全性总结
开发语言·c++
wljy19 小时前
二、静态库的制作和使用
linux·c语言·开发语言·c++