System.Timers。计时器vs System.Threading.Timer

时间:2022-09-09 20:36:34

I have been checking out some of the possible timers lately, and the Threading.Timer and Timers.Timer are the ones that look needful to me (since they support thread pooling).

我最近一直在检查一些可能的计时器和线程。计时器,计时器。Timer对我来说是必要的(因为它们支持线程池)。

I am making a game, and I plan on using all types of events, with different intervals, etc.

我正在做一个游戏,我计划使用所有类型的事件,不同的间隔等等。

Which would be the best?

哪个最好?

8 个解决方案

#1


321  

This article offers a fairly comprehensive explanation:

这篇文章给出了一个相当全面的解释:

"Comparing the Timer Classes in the .NET Framework Class Library" - also available as a .chm file

“在。net Framework类库中比较计时器类”——也可以作为.chm文件使用

The specific difference appears to be that System.Timers.Timer is geared towards multithreaded applications and is therefore thread-safe via its SynchronizationObject property, whereas System.Threading.Timer is ironically not thread-safe out-of-the-box.

具体的区别似乎是system . timer。Timer面向多线程应用程序,因此通过它的SynchronizationObject属性是线程安全的,而System.Threading则是线程安全的。具有讽刺意味的是,Timer不是线程安全的开箱即用的。

I don't believe that there is a difference between the two as it pertains to how small your intervals can be.

我不相信这两者之间有什么区别,因为它与你的时间间隔有多小有关。

#2


130  

System.Threading.Timer is a plain timer. It calls you back on a thread pool thread (from the worker pool).

System.Threading。Timer是普通的Timer。它在线程池线程(从工作线程池)上调用您。

System.Timers.Timer is a System.ComponentModel.Component that wraps a System.Threading.Timer, and provides some additional features used for dispatching on a particular thread.

System.Timers。定时器是一个System.ComponentModel。包装系统的组件。计时器,并提供一些用于在特定线程上调度的附加功能。

System.Windows.Forms.Timer instead wraps a native message-only-HWND and uses Window Timers to raise events in that HWNDs message loop.

System.Windows.Forms。Timer相反地包装了一个本地消息—hwnd,并使用窗口计时器在该HWNDs消息循环中引发事件。

If your app has no UI, and you want the most light-weight and general-purpose .Net timer possible, (because you are happy figuring out your own threading/dispatching) then System.Threading.Timer is as good as it gets in the framework.

如果您的应用程序没有UI,并且您希望尽可能使用最轻量级和通用的。net定时器(因为您很乐意自己设计线程/调度),那么就使用System.Threading。定时器在框架中表现得很好。

I'm not fully clear what the supposed 'not thread safe' issues with System.Threading.Timer are. Perhaps it is just same as asked in this question: Thread-safety of System.Timers.Timer vs System.Threading.Timer, or perhaps everyone just means that:

我不太清楚System.Threading所谓的“不线程安全”问题是什么。计时器。也许这和在这个问题中被问到的一样:system . timer的线程安全。计时器vs System.Threading。定时器,或者也许每个人都是这个意思:

  1. it's easy to write race conditions when you're using timers. E.g. see this question: Timer (System.Threading) thread safety

    在使用计时器时,很容易编写竞争条件。请看这个问题:定时器(System.Threading)线程安全

  2. re-entrancy of timer notifications, where your timer event can trigger and call you back a second time before you finish processing the first event. E.g. see this question: Thread-safe execution using System.Threading.Timer and Monitor

    重新进入计时器通知,其中您的计时器事件可以在处理第一个事件之前触发并再次调用您。请看这个问题:使用System.Threading线程安全的执行。计时器和监控

#3


111  

In his book "CLR Via C#", Jeff Ritcher discourages using System.Timers.Timer, this timer is derived from System.ComponentModel.Component, allowing it to be used in design surface of Visual Studio. So that it would be only useful if you want a timer on a design surface.

在他的书“CLR Via c#”中,Jeff Ritcher不提倡使用system . timer。定时器,这个定时器来自System.ComponentModel。组件,允许在Visual Studio的设计界面中使用。因此,只有当你想在设计表面上安装计时器时,它才有用。

He prefers to use System.Threading.Timer for background tasks on a thread pool thread.

他更喜欢使用System.Threading。线程池线程上的后台任务的计时器。

#4


26  

System.Timers.Timer seems to be deprecated with .NET Core and ASP.NET Core. So try using System.Threading.Timer in future apps.

System.Timers。使用。net Core和ASP不支持Timer。净的核心。所以试着用System.Threading。定时器在未来的应用。


EDIT: OK, let me be more precise:

编辑:好的,让我更准确地说:

With the new .NET Core Framework, Microsoft discontinued some technologies of .NET Framework. To understand that: .NET Core is a totally new framework - rewritten, cross platform, etc. I don't want to go to deep here in detail - please read the .NET Blog.

在新的。net核心框架下,微软停止了一些。net框架的技术。要理解这一点:. net Core是一个全新的框架——重写、跨平台等等。

On the blog is a good article abound porting to .NET Core which explains also the difficulties you can hit. One part of this is to use the .NET Portability Analyzer Visual Studio Add-In and fix the errors you get.

在博客上有一篇很好的文章,大量的移植到。net Core,这也解释了你可能遇到的困难。其中一个部分是使用。net可移植性分析器Visual Studio外接程序并修复您得到的错误。

For the System.Timers.Timer class, it said, that .NET Framework,Version=v4.6.2 is supported, but .NET Core,Version=v5.0 and .NETPlatform,Version=v5.0 is not. Recommended changes: Use System.Threading.Timer.

System.Timers。定时器类,它说,. net框架,版本=v4.6.2支持,但是。net核心,版本=v5.0和。netplatform,Version=v5.0不支持。建议修改:使用System.Threading.Timer。

So that looks for me that System.Timers.Timer is gone for .NET Core.

这就是系统。timer。net核心的定时器已经消失了。

P.S.: But it might come back - Microsoft announced that they want to make some changes to CoreCLR (the name of the framework you use for .NET Core) to make the porting effort easier.

注::但是它可能会回来——微软宣布他们希望对CoreCLR(你使用的。net Core框架的名称)做一些更改,以使移植工作更容易。

#5


22  

I found a short comparison from MSDN

我找到了MSDN的一个简短的比较

The .NET Framework Class Library includes four classes named Timer, each of which offers different functionality:

.NET Framework类库包含四个名为Timer的类,每个类都提供不同的功能:

System.Timers.Timer, which fires an event and executes the code in one or more event sinks at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.

System.Timers。Timer,按一定的间隔触发事件并在一个或多个事件中执行代码。该类用于在多线程环境中作为基于服务器或服务组件使用;它没有用户界面,在运行时不可见。

System.Threading.Timer, which executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.

System.Threading。定时器,它在线程池线程上定期执行一个回调方法。当计时器实例化且不能更改时,将定义回调方法。像System.Timers。定时器类,这个类用于在多线程环境中作为基于服务器或服务组件使用;它没有用户界面,在运行时不可见。

System.Windows.Forms.Timer, a Windows Forms component that fires an event and executes the code in one or more event sinks at regular intervals. The component has no user interface and is designed for use in a single-threaded environment.

System.Windows.Forms。Timer是一个Windows窗体组件,它按一定的间隔触发一个事件并在一个或多个事件接收器中执行代码。该组件没有用户界面,是为在单线程环境中使用而设计的。

System.Web.UI.Timer, an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.

System.Web.UI。定时器,一个ASP。NET组件,以常规间隔执行异步或同步的web页面回发。

#6


18  

One important difference not mentioned above which might catch you out is that System.Timers.Timer silently swallows exceptions, whereas System.Threading.Timer doesn't.

上面没有提到的一个重要区别是system . timer。定时器默默地接受异常,而System.Threading。计时器不。

For example:

例如:

var timer = new System.Timers.Timer { AutoReset = false };
timer.Elapsed += (sender, args) =>
{
    var z = 0;
    var i = 1 / z;
};
timer.Start();

vs

vs

var timer = new System.Threading.Timer(x =>
{
    var z = 0;
    var i = 1 / z;
}, null, 0, Timeout.Infinite);

#7


1  

The two classes are functionally equivalent, except that System.Timers.Timer has an option to invoke all its timer expiration callbacks through ISynchronizeInvoke by setting SynchronizingObject. Otherwise, both timers invoke expiration callbacks on thread pool threads.

这两个类在功能上是等价的,除了system . timer。Timer可以通过ISynchronizeInvoke通过设置SynchronizingObject来调用它所有的计时器过期回调。否则,两个计时器都调用线程池线程上的过期回调。

When you drag a System.Timers.Timer onto a Windows Forms design surface, Visual Studio sets SynchronizingObject to the form object, which causes all expiration callbacks to be called on the UI thread.

拖拽system . timer时。在Windows窗体设计界面上,Visual Studio将SynchronizingObject设置为窗体对象,这将导致在UI线程上调用所有过期回调。

#8


1  

From MSDN: System.Threading.Timer is a simple, lightweight timer that uses callback methods and is served by thread pool threads. It is not recommended for use with Windows Forms, because its callbacks do not occur on the user interface thread. System.Windows.Forms.Timer is a better choice for use with Windows Forms. For server-based timer functionality, you might consider using System.Timers.Timer, which raises events and has additional features.

从MSDN:System.Threading。Timer是一个简单的轻量级计时器,使用回调方法,由线程池线程提供服务。它不建议用于Windows窗体,因为它的回调不会发生在用户界面线程上。System.Windows.Forms。计时器是使用Windows窗体的更好选择。对于基于服务器的计时器功能,您可以考虑使用system . timer。计时器,它会引发事件并具有其他特性。

Source

#1


321  

This article offers a fairly comprehensive explanation:

这篇文章给出了一个相当全面的解释:

"Comparing the Timer Classes in the .NET Framework Class Library" - also available as a .chm file

“在。net Framework类库中比较计时器类”——也可以作为.chm文件使用

The specific difference appears to be that System.Timers.Timer is geared towards multithreaded applications and is therefore thread-safe via its SynchronizationObject property, whereas System.Threading.Timer is ironically not thread-safe out-of-the-box.

具体的区别似乎是system . timer。Timer面向多线程应用程序,因此通过它的SynchronizationObject属性是线程安全的,而System.Threading则是线程安全的。具有讽刺意味的是,Timer不是线程安全的开箱即用的。

I don't believe that there is a difference between the two as it pertains to how small your intervals can be.

我不相信这两者之间有什么区别,因为它与你的时间间隔有多小有关。

#2


130  

System.Threading.Timer is a plain timer. It calls you back on a thread pool thread (from the worker pool).

System.Threading。Timer是普通的Timer。它在线程池线程(从工作线程池)上调用您。

System.Timers.Timer is a System.ComponentModel.Component that wraps a System.Threading.Timer, and provides some additional features used for dispatching on a particular thread.

System.Timers。定时器是一个System.ComponentModel。包装系统的组件。计时器,并提供一些用于在特定线程上调度的附加功能。

System.Windows.Forms.Timer instead wraps a native message-only-HWND and uses Window Timers to raise events in that HWNDs message loop.

System.Windows.Forms。Timer相反地包装了一个本地消息—hwnd,并使用窗口计时器在该HWNDs消息循环中引发事件。

If your app has no UI, and you want the most light-weight and general-purpose .Net timer possible, (because you are happy figuring out your own threading/dispatching) then System.Threading.Timer is as good as it gets in the framework.

如果您的应用程序没有UI,并且您希望尽可能使用最轻量级和通用的。net定时器(因为您很乐意自己设计线程/调度),那么就使用System.Threading。定时器在框架中表现得很好。

I'm not fully clear what the supposed 'not thread safe' issues with System.Threading.Timer are. Perhaps it is just same as asked in this question: Thread-safety of System.Timers.Timer vs System.Threading.Timer, or perhaps everyone just means that:

我不太清楚System.Threading所谓的“不线程安全”问题是什么。计时器。也许这和在这个问题中被问到的一样:system . timer的线程安全。计时器vs System.Threading。定时器,或者也许每个人都是这个意思:

  1. it's easy to write race conditions when you're using timers. E.g. see this question: Timer (System.Threading) thread safety

    在使用计时器时,很容易编写竞争条件。请看这个问题:定时器(System.Threading)线程安全

  2. re-entrancy of timer notifications, where your timer event can trigger and call you back a second time before you finish processing the first event. E.g. see this question: Thread-safe execution using System.Threading.Timer and Monitor

    重新进入计时器通知,其中您的计时器事件可以在处理第一个事件之前触发并再次调用您。请看这个问题:使用System.Threading线程安全的执行。计时器和监控

#3


111  

In his book "CLR Via C#", Jeff Ritcher discourages using System.Timers.Timer, this timer is derived from System.ComponentModel.Component, allowing it to be used in design surface of Visual Studio. So that it would be only useful if you want a timer on a design surface.

在他的书“CLR Via c#”中,Jeff Ritcher不提倡使用system . timer。定时器,这个定时器来自System.ComponentModel。组件,允许在Visual Studio的设计界面中使用。因此,只有当你想在设计表面上安装计时器时,它才有用。

He prefers to use System.Threading.Timer for background tasks on a thread pool thread.

他更喜欢使用System.Threading。线程池线程上的后台任务的计时器。

#4


26  

System.Timers.Timer seems to be deprecated with .NET Core and ASP.NET Core. So try using System.Threading.Timer in future apps.

System.Timers。使用。net Core和ASP不支持Timer。净的核心。所以试着用System.Threading。定时器在未来的应用。


EDIT: OK, let me be more precise:

编辑:好的,让我更准确地说:

With the new .NET Core Framework, Microsoft discontinued some technologies of .NET Framework. To understand that: .NET Core is a totally new framework - rewritten, cross platform, etc. I don't want to go to deep here in detail - please read the .NET Blog.

在新的。net核心框架下,微软停止了一些。net框架的技术。要理解这一点:. net Core是一个全新的框架——重写、跨平台等等。

On the blog is a good article abound porting to .NET Core which explains also the difficulties you can hit. One part of this is to use the .NET Portability Analyzer Visual Studio Add-In and fix the errors you get.

在博客上有一篇很好的文章,大量的移植到。net Core,这也解释了你可能遇到的困难。其中一个部分是使用。net可移植性分析器Visual Studio外接程序并修复您得到的错误。

For the System.Timers.Timer class, it said, that .NET Framework,Version=v4.6.2 is supported, but .NET Core,Version=v5.0 and .NETPlatform,Version=v5.0 is not. Recommended changes: Use System.Threading.Timer.

System.Timers。定时器类,它说,. net框架,版本=v4.6.2支持,但是。net核心,版本=v5.0和。netplatform,Version=v5.0不支持。建议修改:使用System.Threading.Timer。

So that looks for me that System.Timers.Timer is gone for .NET Core.

这就是系统。timer。net核心的定时器已经消失了。

P.S.: But it might come back - Microsoft announced that they want to make some changes to CoreCLR (the name of the framework you use for .NET Core) to make the porting effort easier.

注::但是它可能会回来——微软宣布他们希望对CoreCLR(你使用的。net Core框架的名称)做一些更改,以使移植工作更容易。

#5


22  

I found a short comparison from MSDN

我找到了MSDN的一个简短的比较

The .NET Framework Class Library includes four classes named Timer, each of which offers different functionality:

.NET Framework类库包含四个名为Timer的类,每个类都提供不同的功能:

System.Timers.Timer, which fires an event and executes the code in one or more event sinks at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.

System.Timers。Timer,按一定的间隔触发事件并在一个或多个事件中执行代码。该类用于在多线程环境中作为基于服务器或服务组件使用;它没有用户界面,在运行时不可见。

System.Threading.Timer, which executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.

System.Threading。定时器,它在线程池线程上定期执行一个回调方法。当计时器实例化且不能更改时,将定义回调方法。像System.Timers。定时器类,这个类用于在多线程环境中作为基于服务器或服务组件使用;它没有用户界面,在运行时不可见。

System.Windows.Forms.Timer, a Windows Forms component that fires an event and executes the code in one or more event sinks at regular intervals. The component has no user interface and is designed for use in a single-threaded environment.

System.Windows.Forms。Timer是一个Windows窗体组件,它按一定的间隔触发一个事件并在一个或多个事件接收器中执行代码。该组件没有用户界面,是为在单线程环境中使用而设计的。

System.Web.UI.Timer, an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.

System.Web.UI。定时器,一个ASP。NET组件,以常规间隔执行异步或同步的web页面回发。

#6


18  

One important difference not mentioned above which might catch you out is that System.Timers.Timer silently swallows exceptions, whereas System.Threading.Timer doesn't.

上面没有提到的一个重要区别是system . timer。定时器默默地接受异常,而System.Threading。计时器不。

For example:

例如:

var timer = new System.Timers.Timer { AutoReset = false };
timer.Elapsed += (sender, args) =>
{
    var z = 0;
    var i = 1 / z;
};
timer.Start();

vs

vs

var timer = new System.Threading.Timer(x =>
{
    var z = 0;
    var i = 1 / z;
}, null, 0, Timeout.Infinite);

#7


1  

The two classes are functionally equivalent, except that System.Timers.Timer has an option to invoke all its timer expiration callbacks through ISynchronizeInvoke by setting SynchronizingObject. Otherwise, both timers invoke expiration callbacks on thread pool threads.

这两个类在功能上是等价的,除了system . timer。Timer可以通过ISynchronizeInvoke通过设置SynchronizingObject来调用它所有的计时器过期回调。否则,两个计时器都调用线程池线程上的过期回调。

When you drag a System.Timers.Timer onto a Windows Forms design surface, Visual Studio sets SynchronizingObject to the form object, which causes all expiration callbacks to be called on the UI thread.

拖拽system . timer时。在Windows窗体设计界面上,Visual Studio将SynchronizingObject设置为窗体对象,这将导致在UI线程上调用所有过期回调。

#8


1  

From MSDN: System.Threading.Timer is a simple, lightweight timer that uses callback methods and is served by thread pool threads. It is not recommended for use with Windows Forms, because its callbacks do not occur on the user interface thread. System.Windows.Forms.Timer is a better choice for use with Windows Forms. For server-based timer functionality, you might consider using System.Timers.Timer, which raises events and has additional features.

从MSDN:System.Threading。Timer是一个简单的轻量级计时器,使用回调方法,由线程池线程提供服务。它不建议用于Windows窗体,因为它的回调不会发生在用户界面线程上。System.Windows.Forms。计时器是使用Windows窗体的更好选择。对于基于服务器的计时器功能,您可以考虑使用system . timer。计时器,它会引发事件并具有其他特性。

Source