C# 为什么 .NET 中有 5 个版本的计时器类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10317088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why there are 5 Versions of Timer Classes in .NET?
提问by Mohammed A. Fadil
Why are there five timer classes in the .Net framework, namely the following:
为什么.Net框架中有五个定时器类,分别是:
System.Timers.TimerSystem.Threading.TimerSystem.Windows.Forms.TimerSystem.Web.UI.TimerSystem.Windows.Threading.DispatcherTimer
System.Timers.TimerSystem.Threading.TimerSystem.Windows.Forms.TimerSystem.Web.UI.TimerSystem.Windows.Threading.DispatcherTimer
Why are there several versions of the Timer class? And what are the differences between them?
为什么 Timer 类有多个版本?它们之间有什么区别?
回答by Victor Gorban
Timers.Timergenerates an event after a set interval, with an option to generate recurring events. MSDN
Timers.Timer在设定的时间间隔后生成事件,并提供生成重复事件的选项。MSDN
Windows.Forms.Timeris a Control for winforms.
Windows.Forms.Timer是 winforms 的控件。
Web.UI.Timerperforms asynchronous or synchronous Web page postbacks at a defined interval. MSDN
Web.UI.Timer以定义的时间间隔执行异步或同步网页回发。MSDN
Threading.Timeris the timer for Callbacks. Creates a new Thread for working. Served by thread pool threads. MSDN
Threading.Timer是回调的计时器。创建一个新的工作线程。由线程池线程提供服务。MSDN
So, these timers have different purposes, also they are served by different tools.
因此,这些计时器有不同的用途,它们由不同的工具提供服务。
回答by Bill Tarbell
Here's a description of the primary timers and the points that i find to be the most noteworthy.
以下是对主要计时器的描述以及我认为最值得注意的要点。
Winforms.Timer
Winforms.Timer
- ticks on UI thread not guaranteed to ticket at a specific time
- ticks delayed until UI thread is idle
- will skip ticks if the UI thread is busy
- UI 线程上的滴答声不能保证在特定时间出票
- 滴答延迟直到 UI 线程空闲
- 如果 UI 线程忙,将跳过滴答声
DispatcherTimer
DispatcherTimer
- invoked on UI thread
- can set priority for what level of 'idle' is required to generate a tick
- will skip ticks
- 在 UI 线程上调用
- 可以设置生成滴答声所需的“空闲”级别的优先级
- 将跳过刻度
Threading.Timer
Threading.Timer
- ticks on a worker thread from threadpool - no option for specifying thread
- ticks are always fired on time
- none are skipped - you must guard against new ticks while you're still processing a former tick
- unhandled exceptions will crash the application
- 线程池中的工作线程上的滴答声 - 没有用于指定线程的选项
- 滴答总是准时触发
- 没有被跳过 - 您必须在仍在处理以前的滴答时防范新的滴答声
- 未处理的异常将使应用程序崩溃
Timers.Timer
Timers.Timer
- wrapper around threading timer
- ticks on a worker thread taken from the CLR threadpool
- can force to tick on a specific thread by supplying a SynchronizationObject
- ticks are always fired on time
- none are skipped
- silently eats exceptions
- 线程计时器的包装器
- 从 CLR 线程池中获取的工作线程上的滴答声
- 可以通过提供 SynchronizationObject 强制在特定线程上打勾
- 滴答总是准时触发
- 没有一个被跳过
- 默默地吃异常

