Timers in Windows Service
I want to use timers in my service. But I heard that timers cause deadlock issues. Suppose If I set my timer to start every 10 mins. My service takes 5 mins to finish its current execution. But in some cases it will take more time.(Its unpredictable). So what happens if my service couldn't finish current execution within 10 mins.A new timer event will fire?? And what happens to my current execution of the servic开发者_如何学Goe? Appreciate your help.
you can use timers in Windows service as it also stated on MSDN
A service application is designed to be long running. As such, it usually polls or monitors something in the system. The monitoring is set up in the OnStart method. However, OnStart does not actually do the monitoring. The OnStart method must return to the operating system once the service's operation has begun. It must not loop forever or block. To set up a simple polling mechanism, you can use the System.Timers.Timer component. In the OnStart method, you would set parameters on the component, and then you would set the Enabled property to true. The timer would then raise events in your code periodically, at which time your service could do its monitoring.
despite the above you still need to create your logic to avoid both deadlock or the code specified within the Elapsed
event takes longer then the interval itself.
The Elapsed event is raised on a ThreadPool thread. If processing of the Elapsed event lasts longer than Interval, the event might be raised again on another ThreadPool thread. Thus, the event handler should be reentrant.
http://msdn.microsoft.com/en-us/library/system.timers.timer%28v=vs.80%29.aspx
精彩评论