Workaround for the WaitHandle.WaitAll 64 handle limit?

前端 未结 9 1927
孤独总比滥情好
孤独总比滥情好 2020-11-28 04:19

My application spawns loads of different small worker threads via ThreadPool.QueueUserWorkItem which I keep track of via multiple ManualResetEvent

9条回答
  •  无人及你
    2020-11-28 05:06

    Create a variable that keeps track of the number of running tasks:

    int numberOfTasks = 100;
    

    Create a signal:

    ManualResetEvent signal = new ManualResetEvent(false);
    

    Decrement the number of tasks whenever a task is finished:

    if (Interlocked.Decrement(ref numberOftasks) == 0)
    {
    

    If there is no task remaining, set the signal:

        signal.Set();
    }
    

    Meanwhile, somewhere else, wait for the signal to be set:

    signal.WaitOne();
    

提交回复
热议问题