Search code examples
c#multithreadingwaithandle

Multithreading: WaitAll doesn't wait as expected


I have a thread that is calling two separate threads to do somework. Whenever any of the jobs is finished a Waithandle.Set(0 is called and at the end of the parent worker thread I wanted to WaitAll for both to be finished, before i continue. But priceA() is still coming up first and then PriceB().

new Thread(() =>
                           {
                               new Thread(() =>
                               {
                                   PriceA = _service.GetPriceA();
                                   _waithandle[0].Set();
                               }).Start();

                               new Thread(() =>
                               {
                                   PriceB = _service.GetPriceB();
                                   _waithandle[1].Set();
                               }).Start();

                               WaitHandle.WaitAll(_waithandle);
                           }).Start();
Console.WriteLine("Hello");

What am I missing?

Update:

private EventWaitHandle[] _waithandle;

Ctor:

 _waithandle[0] = new ManualResetEvent(false);
 _waithandle[1] = new ManualResetEvent(false);

Solution

  • new Thread(() =>
                               {
                                   new Thread(() =>
                                   {
                                       _priceA = _service.GetPriceA();
                                       _waithandle[0].Set();
                                   }).Start();
    
                                   new Thread(() =>
                                   {
                                       _priceB = _service.GetPriceB();
                                       _waithandle[1].Set();
                                   }).Start();
    
                                   WaitHandle.WaitAll(_waithandle);
                                   PriceA = _priceA;
                                   PriceB = _priceB;
                               }).Start();
    

    This did the job for me. Culprit was the INotifyChangedProperty() of the PriceA and PriceB which updated the UI too early making my waitall redundant. In case someone else has a similar issue...