Search code examples
.net-3.5timer

System.Timers.Timer event handlers threading mode


Can't find the answer to my question in MSND:
Does Timer class guarantees that all handlers subscribed to Elapsed event will be executed on the same threadpool thread? If yes, will they be executed according the order in which they were added to Elapsed event?


Solution

  • As far as I can see, the only way to ensure that the Elapsed event handlers are all on the same thread is to set the Timer's SynchronizingObject property (usually to a control or something on a form, so that the Elapsed event is handled on the UI thread). Otherwise the event is handled on a threadpool thread, meaning it might be the same thread each time but almost certainly won't be.

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

    The order of the event handlers firing is probably going to be in the order you add them, but this isn't guaranteed and may change in the future. If your design is dependent upon the events being fired in a particular order, you should change your design.