System.Timers.Timer vs System.Threading.Timer

.NetTimer

.Net Problem Overview


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

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

Which would be the best?

.Net Solutions


Solution 1 - .Net

This article offers a fairly comprehensive explanation:

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

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.

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

Solution 2 - .Net

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

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.Windows.Forms.Timer instead wraps a native message-only-HWND and uses Window Timers to raise events in that HWNDs message loop.

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.

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: https://stackoverflow.com/questions/19577296/thread-safety-of-system-timers-timer-vs-system-threading-timer, or perhaps everyone just means that:

  1. it's easy to write race conditions when you're using timers. E.g. see this question: https://stackoverflow.com/questions/3054056/timer-system-threading-thread-safety

  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: https://stackoverflow.com/questions/5124252/thread-safe-execution-using-system-threading-timer-and-monitor

Solution 3 - .Net

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.

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

Solution 4 - .Net

Information from Microsoft about this (see Remarks on MSDN):

> * 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.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.Windows.Forms.Timer > (.NET Framework only), 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; it executes on the UI thread. > * System.Web.UI.Timer > (.NET Framework only), an ASP.NET component that performs asynchronous > or synchronous web page postbacks at a regular interval.

It is interesting to mention that System.Timers.Timer was deprecated with .NET Core 1.0, but was implemented again in .NET Core 2.0 (/ .NET Standard 2.0). The goal with .NET Standard 2.0 was that it should be as easy as possible to switch from the .NET Framework which is probably the reason it came back.

When it was deprecated, the .NET Portability Analyzer Visual Studio Add-In recommended to use System.Threading.Timer instead.

Looks like that Microsoft favors System.Threading.Timer before System.Timers.Timer.

EDIT NOTE 2018-11-15: I hand to change my answer since the old information about .NET Core 1.0 was not valid anymore.

Solution 5 - .Net

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.

For example:

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

vs

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

Solution 6 - .Net

I found a short comparison from MSDN

> The .NET Framework Class Library includes four classes named Timer, > each of which offers different functionality: > > 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.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.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.Web.UI.Timer, an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.

Solution 7 - .Net

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.

[Source][1]

[1]: https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=EN-US&k=k(System.Threading.Timer);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5.2);k(DevLang-csharp)&rd=true "Source"

Solution 8 - .Net

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.

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.

Solution 9 - .Net

As other mentioned the link to MS Docs, one major difference between System.Timers.Timer and System.Threading.Timer is that System.Threading.Timer executes a single callback method defined once while the System.Timers.Timer reacts on events, so supports multiple subscribers which can be also removed.

As also mentioned above, the System.Timers.Timer is using a System.Threading.Timer internally, with e.g. the Enable=false disposing the internal timer, and re creates it on Enable=true / Start(): https://source.dot.net/#System.ComponentModel.TypeConverter/System/Timers/Timer.cs

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTheAJView Question on Stackoverflow
Solution 1 - .NetDavid AndresView Answer on Stackoverflow
Solution 2 - .NetTim Lovell-SmithView Answer on Stackoverflow
Solution 3 - .NetHeroView Answer on Stackoverflow
Solution 4 - .Netice1e0View Answer on Stackoverflow
Solution 5 - .NetstovrozView Answer on Stackoverflow
Solution 6 - .NetdefaultView Answer on Stackoverflow
Solution 7 - .NetGreg GumView Answer on Stackoverflow
Solution 8 - .NetEdward BreyView Answer on Stackoverflow
Solution 9 - .NetEricBDevView Answer on Stackoverflow