Search code examples
c#multithreadingbackgroundworkerthreadpool

Know when ThreadPool is empty


I can;t seem to find an easy way to determine when a ThreadPool has finished with all the queued tasks. I found some answers here but none of which can help me.

For sake of simplicity let's say:

for (int i=0;i<10;i++)
{
   threadpool.queueuserworkitem(Go);

}
void Go()
{
   Console.WriteLine("Hello");
}

So how would I go about sending a final "All done" console.writeline after all the 10 background threads have finished?

Thanks


Solution

  • It is impossible and dangerous to rely on thread pool emptiness. What you can do is to count your active tasks yourself. A low level approach with monitor:

       class Program
        {
            static object _ActiveWorkersLock = new object();
            static int _CountOfActiveWorkers;
    
            static void Go(object state)
            {
                try
                {
                    Console.WriteLine("Hello");
                }
                finally
                {
                    lock (_ActiveWorkersLock)
                    {
                        --_CountOfActiveWorkers;
                        Monitor.PulseAll(_ActiveWorkersLock);
                    }
                }
            }
    
            static void Main(string[] args)
            {
                for (int i = 0; i < 10; i++)
                {
                    lock (_ActiveWorkersLock)
                        ++_CountOfActiveWorkers;
                    ThreadPool.QueueUserWorkItem(Go);
                }
    
                lock (_ActiveWorkersLock)
                {
                    while (_CountOfActiveWorkers > 0)
                        Monitor.Wait(_ActiveWorkersLock);
                }
    
                Console.WriteLine("All done");
            }
        }