这篇博客将梳理一下.NET中4个Timer类,及其用法。

1. System.Threading.Timer

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

callback委托将会在period时间间隔内重复执行,state参数可以传入想在callback委托中处理的对象,dueTime标识多久后callback开始执行,period标识多久执行一次callback。

using System.Threading;
// System.Threading.Timer Timer timer = new Timer(delegate
{
Console.WriteLine($"Timer Thread: {Thread.CurrentThread.ManagedThreadId}"); Console.WriteLine($"Is Thread Pool: {Thread.CurrentThread.IsThreadPoolThread}"); Console.WriteLine("Timer Action.");
},
null,
, ); Console.WriteLine("Main Action.");
Console.WriteLine($"Main Thread: {Thread.CurrentThread.ManagedThreadId}"); Console.ReadLine();

Timer回掉方法执行是在另外ThreadPool中一条新线程中执行的。

2. System.Timers.Timer

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

Interval  指定执行Elapsed事件的时间间隔;

Elapsed  指定定期执行的事件;

Enabled  用于Start/Stop Timer;

Start    开启Timer

Stop    停止Timer

System.Timers.Timer timer = new System.Timers.Timer();

timer.Interval = ;

timer.Elapsed += delegate
{
Console.WriteLine($"Timer Thread: {Thread.CurrentThread.ManagedThreadId}"); Console.WriteLine($"Is Thread Pool: {Thread.CurrentThread.IsThreadPoolThread}"); Console.WriteLine("Timer Action"); timer.Stop();
}; timer.Start(); Console.WriteLine("Main Action.");
Console.WriteLine($"Main Thread: {Thread.CurrentThread.ManagedThreadId}"); Console.ReadLine();

Timer Elapsed定期任务是在ThreadPool的线程中执行的。

3. System.Windows.Forms.Timer

Interval  指定执行Elapsed事件的时间间隔;

Tick       指定定期执行的事件;

Enabled  用于Start/Stop Timer;

Start    开启Timer

Stop    停止Timer

使用System.Windows.Forms.Timer来更新窗体中Label内时间,

using System.Windows.Forms;
public Form1()
{
InitializeComponent();
this.Load += delegate
{
Timer timer = new Timer(); timer.Interval = ; 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}");
};
}

Timer Tick事件中执行的事件线程与主窗体的线程是同一个,并没有创建新线程(或者使用ThreadPool中线程)来更新UI。下面将代码做一个改动,使用System.Timers.Timer来更新UI上的时间,代码如下,

public Form1()
{
InitializeComponent(); this.Load += delegate
{
System.Timers.Timer timer = new System.Timers.Timer(); timer.Interval = ; timer.Elapsed += 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}");
};
}

很熟悉的一个错误。因为Label是由UI线程创建的,所以对其进行修改需要在UI线程中进行。System.Timers.Timer中Elasped执行是在ThreadPool中新创建的线程中执行的。所以会有上面的错误。

4. System.Windows.Threading.DispatcherTimer

属性和方法与System.Windows.Forms.Timer类似。

using System.Windows.Threading;

public MainWindow()
{
InitializeComponent(); this.Loaded += delegate
{
//DispatcherTimer DispatcherTimer timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromSeconds(); timer.Start(); Debug.WriteLine($"Main Thread Id: {Thread.CurrentThread.ManagedThreadId}"); timer.Tick += delegate
{
tbTime.Text = DateTime.Now.ToLongTimeString(); Debug.WriteLine($"Timer Thread Id: {Thread.CurrentThread.ManagedThreadId}"); timer.Stop();
};
};
}

DispatcherTimer中Tick事件执行是在主线程中进行的。

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

DispatcherTimer timer = new DispatcherTimer(DispatcherPriority.Send);

感谢您的阅读。

[C#].NET中几种Timer的使用的更多相关文章

  1. .NET中的三种Timer的区别和用法(转)

      最近正好做一个WEB中定期执行的程序,而.NET中有3个不同的定时器.所以正好研究研究.这3个定时器分别是: //1.实现按用户定义的时间间隔引发事件的计时器.此计时器最宜用于 Windows 窗 ...

  2. 转:.NET中的三种Timer的区别和用法(转)

    //1.实现按用户定义的时间间隔引发事件的计时器.此计时器最宜用于 Windows 窗体应用程序中,并且必须在窗口中使用. System.Windows.Forms.Timer // 2.提供以指定的 ...

  3. 【转】.NET中的三种Timer的区别和用法

    最近正好做一个WEB中定期执行的程序,而.NET中有3个不同的定时器.所以正好研究研究.这3个定时器分别是: //1.实现按用户定义的时间间隔引发事件的计时器.此计时器最宜用于 Windows 窗体应 ...

  4. C#中三种定时器对象的比较

    ·关于C#中timer类 在C#里关于定时器类就有3个1.定义在System.Windows.Forms里2.定义在System.Threading.Timer类里3.定义在System.Timers ...

  5. 关于js中两种定时器的设置及清除(转载)

    1.JS中的定时器有两种: window.setTimeout([function],[interval]) 设置一个定时器,并且设定了一个等待的时间[interval],当到达时间后,执行对应的方法 ...

  6. [转]iOS 中几种定时器 - 控制了时间,就控制了一切

    这篇文章是转载内容,原文地址:http://www.cocoachina.com/ios/20150519/11857.html?utm_source=tuicool 这里的知识点,其实在我们日常开发 ...

  7. C#中三种定时器对象的比较 【转】

    https://www.cnblogs.com/zxtceq/p/5667281.html C#中三种定时器对象的比较 ·关于C#中timer类 在C#里关于定时器类就有3个1.定义在System.W ...

  8. Android中几种常用的定时器和延时方法

    通过实际项目的练习,掌握了几种android基本定时器和延时的用法,这里我想总结一下作为自己的收获,下面列出的是比较简洁的模式,方便简单地在程序中直接调用. 一.三种常用的定时器 1.Handler类 ...

  9. asp.net mvc 中 一种简单的 URL 重写

    asp.net mvc 中 一种简单的 URL 重写 Intro 在项目中想增加一个公告的功能,但是又不想直接用默认带的那种路由,感觉好low逼,想弄成那种伪静态化的路由 (别问我为什么不直接静态化, ...

随机推荐

  1. vue自定义指令

    Vue自定义指令: Vue.directive('myDr', function (el, binding) { el.onclick =function(){ binding.value(); } ...

  2. EasyPusher应用

    转自https://github.com/EasyDarwin/EasyPusher 本文仅实际体验一下demo,分析一下如何应用. 1)EasyPusher框图预览 2) EasyPusher应用实 ...

  3. 7Hibernate高级----青软S2SH(笔记)

  4. .htaccess基本语法和应用 (2012-11-09 16:13:47)转载▼

    htaccess基本语法和应用 (2012-11-09 16:13:47) 转载▼ 标签:  htaccess it 分类: 网络 .htaccess是Apache服务器的一个非常强大的分布式配置文件 ...

  5. web app开发利器 - iscroll4 解决方案

    存在即是道理,iscroll会诞生,主要是因为无论是在iphone.ipod.android 或是更早前的移动webkit都没有提供一种原生的方式来支持在一个固定高度的容器内滚动内容, 这个不幸的规则 ...

  6. 我们平时是怎么写html和css的?

    文章的起因,我只是为了回复一个帖子,http://bbs.csdn.net/topics/390908928?page=1 结果,一扯就根本停不下来.索性,一捅为快,反正是周末. 拿到效果图时,有这么 ...

  7. 【原创】CSS高效开发实战:CSS 3、LESS、SASS、Bootstrap、Foundation --读书笔记(5)使用放射渐变制作光影效果

    阴影效果通常用来表现光线投射在物体上的感觉,如果想制作一个如图5.19所示的文字光影效果,就可以使用背景的线性渐变进行构建. 图5.19可以看到有类似光束照射文字的效果,很好地突出了文字.这实现起来很 ...

  8. Java界面设计 Swing(1)

    Java界面设计的用途 开发者可以通过Java SE开发丰富并且强大的具有图形界面的桌面应用程序.也可以设计一些提高效率的工具软件,帮助自己处理机械性工作. Java 的图形界面工具包,可以用于工具类 ...

  9. Maven生命周期小记

    1.Maven生命周期是为了所有的构建过程进行抽象和统一.Maven从大量的项目和构建工具中学习和反思,总结了一套高度完善.易扩展的生命周期.这个生命周期包含了项目的清理.初始化.编译.测试.打包.集 ...

  10. 金字塔Lucas-Kanande光流算法实现

    // Lucas-Kanade method Optical Flow in OpenCV // BJTShang, 2016-12-13 #include <cv.h> #include ...