几种Timer的区别和用法

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

最底层、轻量级的计时器。基于线程池实现的,工作在辅助线程,与主线程无直接关系。

public Timer(TimerCallback callback, object state, int dueTime, int period);

string state=”.”;
//state参数可以传入想在callback委托中处理的对象。可以传递一个AutoRestEvent,在回调函数中向主函数发送信号。
Timer timer=new Timer(TimeMethod,state,100,1000)//100表示多久后开始,1000表示隔多久执行一次。

void TimerMethod(object state)
{Console.Write(state.ToString());}

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

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

System.Timers.Timer和System.Threading.Timer相比,提供了更多的属性。

  1. 针对服务器的服务程序,也是基于线程池实现的,工作在辅助线程。(在Winform中,可通过UI元素的Invoke方法进行线程调用。)
  2. 继承自Compnent,避免了线程池中无法访问主线程中组件的问题。(把SynchronizeObject属性设置成Form对象,方法将会在UI线程执行,效果通System.Form.Timer,可能会使UI阻塞。)
  3. AutoReset属性设置计时器是否在引发Elapsed事件后重新计时,默认为true。如果该属性设为False,则只执行timer_Elapsed方法一次。
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 500;
timer.Elapsed+=new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Start();

private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) 
{ 
    SetTB("a");
}

 private void SetTB(string value)
{
    if (this.InvokeRequired) 
    {
        this.Invoke(new MethodInvok(SetTB), value);
    }
    else
    {
        this.tbTimer.Text = value;
    }
}

3、System.Windows.Forms.Timer  Windows计时器

此计时器直接继承自Component,最宜用于 Windows 窗体应用程序中,并且必须在窗口中使用。执行的效率不高

  1. Windows计时器建立在基于消息的UI线程上运行,精度限定为5ms。Tick事件中执行的事件与主窗体是同一个线程,并没有创建新线程来更新UI。(如果事件关联的方法执行时间较长,UI将失去响应。)
  2. 只有Enable和Internal两个属性和一个Tick事件,可以使用Start()和Stop()方法控制Enable属性。
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。

猜你喜欢

转载自www.cnblogs.com/springsnow/p/9435696.html
今日推荐