Wait for pooled threads to complete

后端 未结 9 626
无人及你
无人及你 2020-12-01 01:35

I\'m sorry for a redundant question. However, I\'ve found many solutions to my problem but none of them are very well explained. I\'m hoping that it will be made clear, he

9条回答
  •  时光取名叫无心
    2020-12-01 02:12

    I think you were on the right track with the ManualResetEvent. This link has a code sample that closely matches what your trying to do. The key is to use the WaitHandle.WaitAll and pass an array of wait events. Each thread needs to set one of these wait events.

       // Simultaneously calculate the terms.
        ThreadPool.QueueUserWorkItem(
            new WaitCallback(CalculateBase));
        ThreadPool.QueueUserWorkItem(
            new WaitCallback(CalculateFirstTerm));
        ThreadPool.QueueUserWorkItem(
            new WaitCallback(CalculateSecondTerm));
        ThreadPool.QueueUserWorkItem(
            new WaitCallback(CalculateThirdTerm));
    
        // Wait for all of the terms to be calculated.
        WaitHandle.WaitAll(autoEvents);
    
        // Reset the wait handle for the next calculation.
        manualEvent.Reset();
    

    Edit:

    Make sure that in your worker thread code path you set the event (i.e. autoEvents1.Set();). Once they are all signaled the waitAll will return.

    void CalculateSecondTerm(object stateInfo)
    {
        double preCalc = randomGenerator.NextDouble();
        manualEvent.WaitOne();
        secondTerm = preCalc * baseNumber * 
            randomGenerator.NextDouble();
        autoEvents[1].Set();
    }
    

提交回复
热议问题