If you use the
System.Threading.ThreadPool object, you know you can create many worker threads. The following code snippet waits until all worker threads have completed, or until the specified timeout.
I use the
System.Threading.ThreadPool extensively when creating Windows services. I usually spawn a worker thread for every service request. When the user attempts to pause or stop the service, I send a message to all threads to shut down, and then, in my main thread, must wait for all the threads to complete. If the service does not wait for all threads to complete, you get a nasty timeout error from Windows claiming the service 'did not respond'. I believe it is more professional to do the waiting in the service and not expose the user to the error dialog.
There are other ways to wait for all threads to complete, but none are as simple and as elegant as the code snippet below.
Using the code
I usually create a method called
WaitForThreads() and define a timeout value (in seconds) as a property of my service class.
WaitForThreads() as the last action in my
OnPause() methods. The timeout value is there just in case some worker thread misbehaves. An additional advantage to using a timeout is that I get to log all cases where the timeout was used - and fix the worker thread behavior.
protected void WaitForThreads()
int maxThreads = 0;
int placeHolder = 0;
int availThreads = 0;
int timeOutSeconds = YourTimeoutPropertyHere;
while (timeOutSeconds > 0)
if (availThreads == maxThreads) break;
Points of Interest
When creating services, make sure you can interrupt executing threads. It is very difficult to stop a service that has runaway threads. I create a separate class to be used by the worker threads and keep track of each thread in a master collection in my service class. Every worker thread class I have has an
Interrupt() method which sets a flag causing the thread to exit.
You can use
Thread.Abort to stop threads - but MSDN documentation recommends against it. In my experience, design your worker thread classes with reasonable checkpoints (preferably before starting any lengthy operations), and when you are waiting on a resource, make sure the service class can interrupt the wait.
Version 1.0, based on an idea suggested by Jeremy Thomas.