C#(082):四种Timer的区别和用法


1、System.Threading.Timer 线程计时器

1、最底层、轻量级的计时器。基于线程池实现的,工作在辅助线程。

2、它并不是内在线程安全的,并且使用起来比其他计时器更麻烦。此计时器通常不适合 Windows 窗体环境。

构造函数:public Timer(TimerCallback callback, object state, int dueTime, int
period);

$1```
    {Console.Write(state.ToString());}

    

    timer.Dispose();//取消timer执行

# 2、System.Timers.Timer 服务器计时器

1、针对服务器的服务程序,基于System.Threading.Timer,被设计并优化成能用于多线程环境。在这种情况下,应该确保事件处理程序不与 UI
交互。在asp.net中一般使用System.Timers.Timer。

2、继承自Compnent,公开了可以 **SynchronizingObject**
```csharp
$1```
    

```csharp
$1```
    
    int inTimer = 0;

            void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)

            {
```csharp
$1```

此计时器直接继承自Component,它经过了专门的优化以便与 Windows 窗体一起使用,并且必须在窗口中使用。

  1. Windows计时器建立在基于消息的UI线程上运行,精度限定为5ms。Tick事件中执行的事件与主窗体是同一个线程(单线程),并且对与 UI 交互是安全的。
  2. 只有Enable和Internal两个属性和一个Tick事件,可以使用Start()和Stop()方法控制Enable属性。
```csharp
    using System.Windows.Forms;

    

    public Form1()

    {

        InitializeComponent();

        this.Load += delegate

        {

            Timer timer = new Timer();

            timer.Interval = 500;

            timer.Tick += delegate

            {

                System.Diagnostics.Debug.WriteLine($"Timer Thread: {System.Threading.Thread.CurrentThread.ManagedThreadId}");

                System.Diagnostics.Debug.WriteLine($"Is Thread Pool: {System.Threading.Thread.CurrentThread.IsThreadPoolThread}");

                this.lblTimer.Text = DateTime.Now.ToLongTimeString();

            };

    

            timer.Start();

            System.Diagnostics.Debug.WriteLine($"Main Thread: {System.Threading.Thread.CurrentThread.ManagedThreadId}");

        };

    }

4. System.Windows.Threading.DispatcherTimer

主要用于WPF中。属性和方法与System.Windows.Forms.Timer类似。DispatcherTimer中Tick事件执行是在主线程中进行的。

使用DispatcherTimer时有一点需要注意,因为DispatcherTimer的Tick事件是排在Dispatcher队列中的,当系统在高负荷时,不能保证在Interval时间段执行,可能会有轻微的延迟,但是绝对可以保证Tick的执行不会早于Interval设置的时间。如果对Tick执行时间准确性高可以设置DispatcherTimer的priority。

相关