Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

15.10. Waiting for All Threads in theThread Pool to Finish

Problem

For threads that are manually created via the Thread class, you can call the Join method to wait for a thread to finish. This works well when you need to wait for all threads to finish processing before an application terminates. Unfortunately, the thread pool threads do not have a Join method. You need to make sure that all threads in the thread pool have finished processing before another thread terminates or your application’s main thread terminates.

Solution

Use a combination of the ThreadPool methods—GetMaxThreads and GetAvailableThreads—to determine when the ThreadPool is finished processing the requests:

public static void Main( ) { for(int i=0;i<25;i++) { // have to wait or threadpool never gives out threads to requests Thread.Sleep(50); // queue thread request ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc),i); } // have to wait here or the background threads in the thread // pool would not run before the main thread exits. Console.WriteLine("Main Thread waiting to complete..."); bool working = true; int workerThreads = 0; int completionPortThreads = 0; int maxWorkerThreads = 0; int maxCompletionPortThreads = 0; // get max threads in the pool ThreadPool.GetMaxThreads(out maxWorkerThreads,out maxCompletionPortThreads); while(working) { // get available threads ThreadPool.GetAvailableThreads(out workerThreads,out completionPortThreads); if(workerThreads == maxWorkerThreads) { // allow to quit working ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata