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

相关推荐
lly20240641 分钟前
HTML与CSS:构建网页的基石
开发语言
一只会写代码的猫44 分钟前
面向高性能计算与网络服务的C++微内核架构设计与多线程优化实践探索与经验分享
java·开发语言·jvm
是小胡嘛2 小时前
C++之Any类的模拟实现
linux·开发语言·c++
csbysj20203 小时前
Vue.js 混入:深入理解与最佳实践
开发语言
Gerardisite5 小时前
如何在微信个人号开发中有效管理API接口?
java·开发语言·python·微信·php
Want5955 小时前
C/C++跳动的爱心①
c语言·开发语言·c++
coderxiaohan5 小时前
【C++】多态
开发语言·c++
gfdhy5 小时前
【c++】哈希算法深度解析:实现、核心作用与工业级应用
c语言·开发语言·c++·算法·密码学·哈希算法·哈希
Eiceblue6 小时前
通过 C# 将 HTML 转换为 RTF 富文本格式
开发语言·c#·html
故渊ZY6 小时前
Java 代理模式:从原理到实战的全方位解析
java·开发语言·架构