c# - Multithreading: WaitAll doesn't wait as expected -


i have thread calling 2 separate threads somework. whenever of jobs finished waithandle.set(0 called , @ end of parent worker thread wanted waitall both finished, before continue. pricea() still coming first , 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 missing?

update:

private eventwaithandle[] _waithandle; 

ctor:

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

you're creating separate thread wait... code after statement you've given continue because you're not waiting in that thread. in other words, you're creating 3 threads:

  • thread x: creates threads , b, waits them finish
  • thread a: gets pricea , sets waithandle[0]
  • thread b: gets priceb , sets waithandle[1]

but thread x doing nothing after it's waited, what's point of waiting within it?

additionally, lot simpler call join on threads you've created. in fact, if need wait in "current" thread, need one thread in first place:

thread t = new thread(() => { pricea = _service.getpricea(); }); t.start(); priceb = _service.getpriceb(); t.join(); // other code 

by time reach "other code", both pricea , priceb have been set. of course, missing considerable amount of error handling... that's easier add when you've got simpler starting point over-complicated code.


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -