Skip to content

Instantly share code, notes, and snippets.

@jabez007
Created April 4, 2018 21:48
Show Gist options
  • Save jabez007/1b89817ceab2ebda289d2ade448b0898 to your computer and use it in GitHub Desktop.
Save jabez007/1b89817ceab2ebda289d2ade448b0898 to your computer and use it in GitHub Desktop.
ThreadPool WaitForThreads
/// <summary>
/// https://www.codeproject.com/articles/8398/wait-for-threads-in-a-threadpool-object-to-complet
/// 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 = 30;
//Now wait until all threads from the Threadpool have returned
while (timeOutSeconds > 0)
{
//figure out what the max worker thread count it
ThreadPool.GetMaxThreads(out maxThreads, out placeHolder);
ThreadPool.GetAvailableThreads(out availThreads, out placeHolder);
if (availThreads == maxThreads) break;
// Sleep
Thread.Sleep(TimeSpan.FromMilliseconds(1000));
--timeOutSeconds;
}
// You can add logic here to log timeouts
if (timeOutSeconds <= 0)
{
Globals.logger.Error("Timeout waiting for working threads to finish");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment