Wait for pooled threads to complete

后端 未结 9 599
无人及你
无人及你 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:07

    I've found a good solution here :

    http://msdn.microsoft.com/en-us/magazine/cc163914.aspx

    May come in handy for others with the same issue

    0 讨论(0)
  • 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();
    }
    
    0 讨论(0)
  • 2020-12-01 02:12

    Using .NET 4.0 Barrier class:

            Barrier sync = new Barrier(1);
    
            foreach(var o in collection)
            {
                WaitCallback worker = (state) => 
                {
                    // do work
                    sync.SignalAndWait();
                };
    
                sync.AddParticipant();
                ThreadPool.QueueUserWorkItem(worker, o);
            }
    
            sync.SignalAndWait();
    
    0 讨论(0)
提交回复
热议问题