Timer的用法: System.Threading.Timer 和 System.Timers.Timer

本文详细比较了.NET中System.Threading.Timer和System.Timers.Timer的异同,涉及使用场景、回调处理、线程模型、同步上下文、准确性以及控制方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Threading;

class Program
{
    static void Main()
    {
    	// Timer timer = new Timer(TimerCallback, null, delayMilliseconds, intervalMilliseconds);
		// You can pass an optional state object (of type object) that will be passed to the callback method. If you don't need it, you can pass null.
        Timer timer = new Timer(TimerCallback, null, 0, 1000); // Execute every 1 second

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

		timer.Change(delayMilliseconds, intervalMilliseconds);
		timer.Change(Timeout.Infinite, Timeout.Infinite);

    }

    private static void TimerCallback(object state)
    {
        Console.WriteLine("Timer elapsed at: " + DateTime.Now);
    }
}

using System;
using System.Timers;

class Program
{
    static void Main()
    {
        Timer timer = new Timer();
        timer.Interval = 1000; // 1 second
        timer.Elapsed += TimerElapsedEventHandler;
        timer.Start();

        Console.WriteLine("Press Enter to exit.");
        Console.ReadLine();
        
		timer.Stop();
    }

    private static void TimerElapsedEventHandler(object sender, ElapsedEventArgs e)
    {
        Console.WriteLine("Timer elapsed at: " + DateTime.Now.ToString("HH:mm:ss"));
    }
}

System.Threading.Timer and System.Timers.Timer are two timer classes in .NET that allow you to execute code at specified intervals. They have some differences in terms of usage and behavior:

  1. Namespace:

    • System.Threading.Timer is part of the System.Threading namespace.
    • System.Timers.Timer is part of the System.Timers namespace.
  2. Threading Model:

    • System.Threading.Timer is a lightweight timer that uses the thread pool for executing its timer callbacks. This means that the callback method you provide to this timer runs on a thread from the thread pool.
    • System.Timers.Timer, on the other hand, is a more feature-rich timer and is designed to work with multi-threaded applications. It uses its own thread for executing timer callbacks.
  3. Callback Delegate:

    • System.Threading.Timer uses a TimerCallback delegate for its callback method, which takes an Object parameter.
    • System.Timers.Timer uses an ElapsedEventHandler delegate for its callback method, which takes two parameters: the sender (usually the timer itself) and an ElapsedEventArgs object.
  4. Synchronization Context:

    • System.Timers.Timer captures and propagates the synchronization context of the thread that created it. This means that if you create a System.Timers.Timer on an UI thread, the timer’s callback will run on the UI thread by default.
    • System.Threading.Timer does not capture or propagate the synchronization context, so its callback will run on a thread pool thread without any synchronization context.
  5. Accuracy:

    • System.Timers.Timer is generally more accurate than System.Threading.Timer because it uses a separate thread for timer operations. However, its accuracy can still be affected by system load and other factors.
  6. Start and Stop:

    • Both timers provide methods to start and stop the timer. In System.Threading.Timer, you can use the Change method to modify the due time and interval after the timer is created.
    • System.Timers.Timer provides Start and Stop methods for starting and stopping the timer, and you can change the interval and enable or disable it without recreating the timer.
  7. Disposed Event:

    • System.Timers.Timer includes a Disposed event that can be useful for cleanup operations when the timer is disposed of.

In summary, the choice between System.Threading.Timer and System.Timers.Timer depends on your specific requirements and the threading model of your application. If you need a simple timer for background tasks and are comfortable with thread pool behavior, System.Threading.Timer may be sufficient. If you need more control, accuracy, or want to run the timer on a specific synchronization context (such as a UI thread), System.Timers.Timer might be a better choice.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值