Solved

How should I know that all threads in threapool are done. I am creating threadpool threads in loop?

Posted on 2007-12-03
3
487 Views
Last Modified: 2013-12-16
I am creating threads in a loop.
for (int i = 0 ; i++, i<20)
 ThreadPool.QueueUserWorkItem(new WaitCallBack(SomeMethod), someobjectpassessomeinfoToMethod );
next

'Here I need to wait until all above threads are done with their processing

How to determine whether all threads are done.

0
Comment
Question by:scvens
3 Comments
 
LVL 10

Accepted Solution

by:
Nash2334 earned 100 total points
ID: 20397068
I have accomplished something similar using BackgroundWorkers by adding the workers to a list and then checking the IsBusy property:

int m = 1000;
private List<BackgroundWorker> bwList = new List<BackgroundWorker>();

private void StartWorkers
{
            BackgroundWorker bw;

            for (int i = 0; i < 10; i++)
            {
                bw = new BackgroundWorker();
                bw.DoWork += new DoWorkEventHandler(bw_DoWork);
                bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
                bwList.Add(bw);
                bw.RunWorkerAsync();
            }
}

        private bool CheckWorkers()
        {
            foreach (BackgroundWorker w in bwList)
            {
                if (w.IsBusy)
                    return false;
            }

            return true;
        }
0
 
LVL 18

Assisted Solution

by:jcoehoorn
jcoehoorn earned 75 total points
ID: 20398350
WaitHandle waitHandles[20];
for (int i = 0 ; i++, i<20)
    waitHandles[i] = new AutoResetEvent(false);
    ThreadPool.QueueUserWorkItem(new WaitCallBack(SomeMethod), waitHandles[i] );
next
WaitHandle.WaitAll(waitHandles);
0
 
LVL 4

Assisted Solution

by:rafd123
rafd123 earned 75 total points
ID: 20426006
The most elegant solution to this is to use the Interlocked funtions to provide lock-free notification of when all threads are complete. The strategy involves decrementing a counter using Interlocked.Decrement within each worker method; the first worker to reach 0 can execute some completion code (e.g. fire a completion event)

Example:




using System;

using System.Threading;
 

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            int total = 20;

            int pending = total;

            for(int i = 0; i < total; ++i)

            {

                ThreadPool.QueueUserWorkItem(delegate(object state)

                {

                    // Do some work here

                    Console.WriteLine("Hello world. My thread ID is {0}", Thread.CurrentThread.ManagedThreadId);
 

                    if(0 == Interlocked.Decrement(ref pending))

                    {

                        // Perform completion work here

                        Console.WriteLine("All Done!");

                    }

                }, null);

            }
 

            Console.ReadLine();

        }

    }

}

Open in new window

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Connection String 16 43
Allow user to hide and show datagridview columns 4 17
Close tabpage of custom control 9 23
Get Client IP on RDS - VB.NET 15 25
Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
This is used to tweak the memory usage for your computer, it is used for servers more so than workstations but just be careful editing registry settings as it may cause irreversible results. I hold no responsibility for anything you do to the regist…

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

26 Experts available now in Live!

Get 1:1 Help Now