Click here to Skip to main content
13,596,952 members
Click here to Skip to main content
Add your own
alternative version


25 bookmarked
Posted 27 Sep 2004

Wait for threads in a ThreadPool object to complete

, 27 Sep 2004
Rate this:
Please Sign up or sign in to vote.
A small code snippet to wait for all ThreadPool worker threads to complete.


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.

I call WaitForThreads() as the last action in my OnStop() and 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.

/// <summary>
/// Blocks until all worker threads have returned to the thread pool.
/// A good timeout value is 30 seconds.
/// </summary>
protected void WaitForThreads()
    int    maxThreads   = 0;
    int    placeHolder  = 0;
    int    availThreads = 0;
    int    timeOutSeconds = YourTimeoutPropertyHere;

    //Now wait until all threads from the Threadpool have returned
    while (timeOutSeconds > 0)
        //figure out what the max worker thread count it
                             maxThreads,out placeHolder);
        System.Threading.ThreadPool.GetAvailableThreads(out availThreads, 
                                                       out placeHolder);

        if (availThreads == maxThreads) break;
        // Sleep
    // You can add logic here to log timeouts

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.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Web Developer
United States United States
Giora Tamir has been Architecting, Designing and Developing software and hardware solutions for over 15 years. As an IEEE Senior member and a talented developer, Giora blends software development, knowledge of protocols, extensive understanding of hardware and profound knowledge of both Unix and Windows based systems to provide a complete solution for both defense and commercial applications. Giora, also known as G.T., now holds the position of Principal Engineer for ProfitLine, Inc. architecting the next generation of .NET applications based on a Service-Oriented-Architecture.

Gioras areas of interest include distributed applications, networking and cryptography in addition to Unix internals and embedded programming.

Founded in 1992, ProfitLine manages hundreds of millions of dollars in annual telecom spend for its prestigious Fortune 1000 client base, such as Merrill Lynch, Charming Shoppes, Macromedia, CNA Financial Corporation, and Constellation Energy Group. ProfitLine's outsourced solution streamlines telecom administrative functions by combining a best practices approach with intelligent technology. For more information about ProfitLine, call 858.452.6800 or e-mail <a>

You may also be interested in...

Comments and Discussions

QuestionPoolGuard Pin
Alsarg723-Dec-11 22:05
memberAlsarg723-Dec-11 22:05 
Generalthreadpool doubt Pin
carlos_rocha6-Jan-05 1:26
membercarlos_rocha6-Jan-05 1:26 
GeneralIs there any guarantee... Pin
Rolf Schaeuble28-Sep-04 4:41
memberRolf Schaeuble28-Sep-04 4:41 
GeneralRe: Is there any guarantee... Pin
gtamir28-Sep-04 4:48
membergtamir28-Sep-04 4:48 
GeneralRe: Is there any guarantee... Pin
Gary DesRoches28-Sep-04 4:52
memberGary DesRoches28-Sep-04 4:52 
GeneralRe: Is there any guarantee... Pin
Rolf Schaeuble28-Sep-04 5:18
memberRolf Schaeuble28-Sep-04 5:18 
GeneralRe: Is there any guarantee... Pin
gtamir28-Sep-04 9:21
membergtamir28-Sep-04 9:21 
GeneralRe: Is there any guarantee... Pin
Gary DesRoches28-Sep-04 9:54
memberGary DesRoches28-Sep-04 9:54 
GeneralRe: Is there any guarantee... Pin
gtamir28-Sep-04 9:24
membergtamir28-Sep-04 9:24 
GeneralRe: Is there any guarantee... Pin
phyl4-Oct-04 22:02
memberphyl4-Oct-04 22:02 
GeneralRe: Is there any guarantee... Pin
gtamir5-Oct-04 20:04
membergtamir5-Oct-04 20:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01-2016 | 2.8.180621.3 | Last Updated 28 Sep 2004
Article Copyright 2004 by gtamir
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid