be notified when all background threadpool threads are finished

后端 未结 7 1905
星月不相逢
星月不相逢 2020-12-16 01:37

I have a scenario when I start 3..10 threads with ThreadPool. Each thread does its job and returns to the ThreadPool. What are possible options to be notified in main thread

7条回答
  •  执念已碎
    2020-12-16 02:25

    If its not more than 64 Threads to wait on, you can use the WaitHandle.WaitAll method like this:

    List events = new List();
    for (int i = 0; i < 64; i++)
    {
        ManualResetEvent mre = new ManualResetEvent(false);
        ThreadPool.QueueUserWorkItem(
            delegate(object o)
            {
                Thread.Sleep(TimeSpan.FromMinutes(1));
                ((ManualResetEvent)o).Set();
            },mre);
        events.Add(mre);
    }
    WaitHandle.WaitAll(events.ToArray());
    

    The execution will wait till all ManualResetEvents are set, alternatively, you may use WaitAny method.

    The WaitAny and WaitAll methods will block the execution, but you can simply use the list, or a dictionary of ManualResetEvents linked to the task that is spawn for later determining if the thread is done though.

提交回复
热议问题