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

相关推荐
偶尔的鼠标人32 分钟前
SqlSugar查询字符串转成Int的问题
c#·sqlsugar
我不是程序猿儿34 分钟前
【C#】WinForms 控件句柄与 UI 刷新时机
开发语言·ui·c#
十五年专注C++开发1 小时前
Qt-Nice-Frameless-Window: 一个跨平台无边框窗口(Frameless Window)解决方案
开发语言·c++·qt
凯歌的博客1 小时前
python虚拟环境应用
linux·开发语言·python
祈祷苍天赐我java之术1 小时前
如何在Java中整合Redis?
java·开发语言·redis
froginwe112 小时前
HTML5 测验
开发语言
野生技术架构师4 小时前
牛客网Java 高频面试题总结(2025最新版)
java·开发语言·面试
一只鹿鹿鹿4 小时前
系统安全设计方案书(Word)
开发语言·人工智能·web安全·需求分析·软件系统
持梦远方4 小时前
【C++日志库】启程者团队开源:轻量级高性能VoyLog日志库完全指南
开发语言·c++·visual studio
聪明努力的积极向上4 小时前
【C#】HTTP中URL编码方式解析
开发语言·http·c#