0

Lets say I have a Timer which has the Elapsed event handled. What thread is the method code executed on?

Is is the thread that the timer was created on? If so, that means if I wish it to be on another thread I have to ensure that the timer gets created in the threads main loop rather than the initialization of the thread - correct?

Cheetah
  • 13,785
  • 31
  • 106
  • 190

1 Answers1

1

The thread is one out of the threadpool. There is no way to prodict which thread will be associated with the elapsed method.

Details: http://msdn.microsoft.com/en-us/library/system.timers.timer.elapsed.aspx

(And it should not matter, from a designs perspective)

Edit: Actually there is a method to define which thread is used; You can used the SynchronizingObject property of the timer:

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

When the Elapsed event is handled by a visual Windows Forms component, such as a button, accessing the component through the system-thread pool might result in an exception or just might not work. Avoid this effect by setting SynchronizingObject to a Windows Forms component, which causes the method that handles the Elapsed event to be called on the same thread that the component was created on.

See: http://msdn.microsoft.com/en-us/library/system.timers.timer.synchronizingobject.aspx

Mario The Spoon
  • 4,799
  • 1
  • 24
  • 36
  • So theoretically speaking, if you have a single thread in your application and 10 different `Timer` objects, the `Elapsed` event for each of them would run on the same single thread. – Cheetah Dec 05 '12 at 17:02
  • No. Every applicatino has a thread pool that is created by the .NET runtime itself. One of these threads is used. Unless you specify the SynchronizingoObject there is no way to predict on which thread Elapsed will be called. – Mario The Spoon Dec 06 '12 at 06:35
  • If I have Thread A which creates Object B and 2 timers which have B as the SynchornizingObject and one timer elapses during the executing of the other timers elapsed event handler method, does some sort of queue form, or does something else happen? or is it undefined behavior? – Cheetah Dec 06 '12 at 10:23
  • I have not tries this, but as far as the documentation goes I understand the both elapsed will be called on thread A in an ordered ways (that is one after another) – Mario The Spoon Dec 06 '12 at 12:54