5

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

3 Answers 3

4

You wouldn't ask the thread pool, but instead you would get each background thread to provide notification of when it completes.

But don't do that plumbing yourself, use the new TPL and the Task class:

var tasks = new Task[10];
for (int i=0;i<10;i++)
{
    tasks[i] = Task.Factory.StartNew( Go );
}

Task.WaitAll(tasks);
Console.WriteLine("All done");

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

EDIT: I would question why you want exactly 10 threads performing the work. The default task scheduler already optimizes for the number of CPU cores detected. But if you must, there is an implementation of a TaskScheduler that limits the degree of concurrency to a fixed number here: http://msdn.microsoft.com/en-us/library/ee789351.aspx

5
  • That would work, but I need something where I can queue around 500 tasks, and only execute 10 at a time (10 threads only), so the rest would be queued and wait for a thread to get freed up. Any other ideas?
    – Darko
    Feb 25, 2012 at 5:42
  • Task's use an underlying thread pool. The default number of threads is based on the machine's CPU count, but if you want explicit control over the number of threads that is also possible with a custom TaskScheduler.
    – Tyson
    Feb 25, 2012 at 5:46
  • Use PLINQ together with WithDegreeOfParallelism(10) option.
    – ogggre
    Feb 25, 2012 at 5:47
  • Well I looked around on creating a custom TaskScheduler and it seems a bit too advanced for me. I'll see if I can find my way around, if not I'll go with ogggre's solution
    – Darko
    Feb 25, 2012 at 6:43
  • @Darko See edit above. The other alternative is PLINQ as suggested above (It uses the same TPL library under the covers). The only thing to watch out for with that is that while it performs the work on multiple threads, it blocks the calling thread until complete. So if you want the thread that initiates the work to continue, you have to dispatch the PLINQ query onto another thread anyway (usually using a Task).
    – Tyson
    Feb 25, 2012 at 7:48
1

Have you tried using Reactive Extensions?

Rx makes doing just this very simple. For example, you can rewrite your problem like this:

    private void test()
    {
        var list = Enumerable.Range(0, 10)
            .ToObservable()
            .ObserveOn(Scheduler.ThreadPool)
            .SubscribeOn(Scheduler.ThreadPool)
            .Subscribe(i=>Go(),Done);

    }

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

    void Done()
    {
        Console.WriteLine("Done");
    }

Super simple. Look into Rx, you'll be glad

8
  • I don't think Rx is suitable for this scenario. While it is possible as you have shown, TPL is a much better fit. e.g. how would you cancel all operations? Once finished, how would you determine which 'task's threw exceptions?
    – Tyson
    Feb 25, 2012 at 5:58
  • any resource you would recommend? And please bare in mind I am a beginer
    – Darko
    Feb 25, 2012 at 6:02
  • Rx is perfectly designed for that. There is a third param that you can pass in that is executed when an exception occurs. You can use that to handle and identify exceptions. To cancel the opperation, list is of type IDisposable, just call dispose and the opperation is canceled. Feb 25, 2012 at 6:03
  • Yes, I would watch the videos here: msdn.microsoft.com/en-us/data/gg577611 They are very informative Feb 25, 2012 at 6:04
  • I think your using Rx as a silver bullet. Don't get me wrong, I love Rx and think it's beautiful, but to me TPL and PLINQ fits for this scenario, and produces more understandable code.
    – Tyson
    Feb 25, 2012 at 6:11
0

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");
        }
    }
6
  • This is exactly what I needed. Only one question because I am a bit new to C# and picking up bits and pieces on the way - the only part I couldn't understand was "lock (_ActiveWorkersLock)", the whole implementation of _ActiveWorkersLock, what's its purpose?
    – Darko
    Feb 25, 2012 at 5:47
  • 1
    lock (...) is a monitor primitive, very similar to critical section. _ActiveWorkersLock is just an object, it is used as ID for critical section. Wait and Pulse are methods for waiting and signalling. This makes monitor somewhat similar to conditional variable in POSIX.
    – ogggre
    Feb 25, 2012 at 5:51
  • 2
    But shown approach is low level and may be hard and error-prone. I recommend you to stick with PLINQ and TPL, as suggested in another answer. These technologies will bring the correct exception handling for you too.
    – ogggre
    Feb 25, 2012 at 5:54
  • I would highly recommend against using this approach @Darko. There is a lot more plumbing than this to support cancellation, exception handling, etc, that Tasks and the TPL provide for you.
    – Tyson
    Feb 25, 2012 at 5:54
  • @ogggre - why pulse the monitor if CountOfActiveWorkers has not been decremented to zero? Why should the check for zero have to be done in main()? Feb 25, 2012 at 10:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.