Does a System.Timers.Timer elapse on a separate thread than the thread that created it?
Lets say I have a class with a timer that fires every 5 seconds. When the timer fires, in the elapsed method, some object is modified. Lets say it takes a long time to modify this object, like 10 seconds. Is it possible that I will run into thread collisions in this scenario?
It depends. The System.Timers.Timer
has two modes of operation.
If SynchronizingObject
is set to an ISynchronizeInvoke
instance then the Elapsed
event will execute on the thread hosting the synchronizing object. Usually these ISynchronizeInvoke
instances are none other than plain old Control
and Form
instances that we are all familiar with. So in that case the Elapsed
event is invoked on the UI thread and it behaves similar to the System.Windows.Forms.Timer
. Otherwise, it really depends on the specific ISynchronizeInvoke
instance that was used.
If SynchronizingObject
is null then the Elapsed
event is invoked on a ThreadPool
thread and it behaves similar to the System.Threading.Timer
. In fact, it actually uses a System.Threading.Timer
behind the scenes and does the marshaling operation after it receives the timer callback if needed.