I have a .Net 4.0 C# Windows Service which spawns a number of thread which run continuously. Each thread runs at different intervals based on a timer.
I want to shut these threads down gracefully when the service is shutdown.
Since some of these threads may be waiting for hours to do it’s processing, I need to wake them up and tell them to exit.
I could create a loop in these threads to periodically check some global variable at some interval less that their processing interval, but I would prefer a signaling mechanism which would cause them the timer to pop prematurely.
How can I wake these threads waiting on a timer without using Thread.Abort or Thread.Interrupt?
I’m going to assume that you have a good reason for using independently managed threads to do the work (as opposed to just doing it in the timer’s event). If so, you want to use
WaitHandle.WaitAny()and examine the return value to determine which WaitHandle caused the thread to proceed: