Are C # timers naturally multithreaded?

If I have two system timers that fire events at 10 and 20 seconds respectively, are the event function calls multithreaded? In the scenario below, I have timers that fire events at intervals of 10 and 12 s respectively. It is assumed that the function "My10sEvent" will be called first. If it is a slow function that takes 8 seconds to run, will it block another event (tmr12s), or will the second event fire during 12 seconds?

System.Timers.Timer tmr10s = new System.Timers.Timer(10000.0); tmr10s.Enabled = true; tmr10s.Elapsed += new ElapsedEventHandler(My10sEvent); System.Timers.Timer tmr12s = new System.Timers.Timer(12000.0); tmr12s.Enabled = true; tmr12s.Elapsed += new ElapsedEventHandler(My12sEvent); Thread.Sleep(System.Threading.Timeout.Infinite); //sleep indefinitely to let the above events fire 
+3
source share
3 answers

The CLR uses a dedicated thread to track the active timers of System.Timers.Timer and System.Threading.Timer. The Elapsed event rises to another thread pulled out of the thread.

So yes, they keep ticking without affecting each other. You have to be very careful, it is possible that your Elapsed event handler will be called again while it is still running. This happens when it takes longer than the interval. Or, even worse, when the machine is heavily loaded or you have many active threadpool threads. This can lead to very difficult failure diagnostics if the event handler is not thread safe. It almost never happens. Setting the timer's AutoReset property to false is an easy way to avoid this problem.

+4
source

It doesn't seem to block if you use System.Threading.Timer or call System.Timers.Timer without a SynchronizingObject.

A similar question: Are C # timers running in a separate thread?

+3
source

From the documentation of System.Timers.Timer :

The server timer is designed for use with workflows in a multi-threaded environment. Server timers can move between threads to handle the raised Elapsed event, which leads to greater accuracy than Windows timers during the event popup.

So yes.

Moreover, from the documentation for the properties of System.Timers.Timer.SynchronizingObject :

When SynchronizingObject is null, the method that handles the Elapsed event is called on the thread from the system thread pool. For more information about system thread pools, see ThreadPool.

Thus, events occur in the threads of the thread pool if the SynchronizingObject parameter is not set.

+1
source

Source: https://habr.com/ru/post/1442787/


All Articles