简体   繁体   中英

Wait for threadpool's threads to finish

I've got this method:

/// <summary>
    /// Waits for all threads in the thread pool to be finished.         
    /// </summary>
    /// <param name="maxWaitingTime">Maximum time to wait in seconds</param>
    /// <returns>true if all threads in pool are finished before maxWaitingTime. False if maxWaitingTime is hit </returns>
    public bool WaitForThreads(int maxWaitingTime)
    {
        int maxThreads = 0;
        int placeHolder = 0;
        int availableThreads = 0;

        while (maxWaitingTime > 0)
        {
            System.Threading.ThreadPool.GetMaxThreads(out maxThreads, out placeHolder);
            System.Threading.ThreadPool.GetAvailableThreads(out availableThreads, out placeHolder);

            //Stop if all threads are available
            if (availableThreads == maxThreads)
            {
                return true;
            }

            System.Threading.Thread.Sleep(TimeSpan.FromMilliseconds(1000));
            --maxWaitingTime;            
        }

        return false;
    }

I'm using this in a console application to wait for a while so all tasks that threadpool is handling are finished. I've set the max threads to 8, but somehow the available threads never reach the max threads, there is always one thread still busy.

I'm thinking that somehow this method is called within the thread pool, even if I call this method directly from the program.cs.

How can I see in the threads window of visual studio if a thread is run in the thread pool?

That's not what "maxThreads" means. The job of the threadpool scheduler is to keep the number of active threads equal to "minThreads". Only when those threads don't complete in a reasonable amount of time (reasonable is half a second), then the scheduler makes another thread available to try to work down the backlog. The "maxThreads" value sets an upper bound on how many additional threads it makes available.

So what you really want to test is to check if the number of available threads is equal or larger to "minThreads".

This is a very bad practice, decent odds that your code will just deadlock. Which will happen when the code gets accidentally in sync with a Timer or TP threads that you just don't know about because they got started by .NET Framework code. Waiting for TP threads to complete reliably requires writing explicit code to check for the condition, those threads must signal a synchronization object when they exit so you can use WaitHandle.WaitAll(). Best done with the Task.WaitAll() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM