c# - Comparison of Join and WaitAll -


for multiple threads wait, can compare pros , cons of using waithandle.waitall , thread.join?

waithandle.waitall has 64 handle limit huge limitation. on other hand, convenient way wait many signals in single call. thread.join not require creating additional waithandle instances. , since called individually on each thread 64 handle limit not apply.

personally, have never used waithandle.waitall. prefer more scalable pattern when want wait on multiple signals. can create counting mechanism counts or down , once specific value reach signal single shared event. countdownevent class conveniently packages of single class.

var finished = new countdownevent(1); (int = 0; < num_work_items; i++) {   finished.addcount();   spawnasynchronousoperation(     () =>     {       try       {         // place logic run in parallel here.       }             {         finished.signal();       }     } } finished.signal(); finished.wait(); 

update:

the reason why want signal event main thread subtle. basically, want treat main thread if work item. afterall, it, along other real work items, running concurrently well.

consider moment might happen if did not treat main thread work item. go through 1 iteration of for loop , add count our event (via addcount) indicating have 1 pending work item right? lets spawnasynchronousoperation completes , gets work item queued on thread. now, imagine if main thread gets preempted before swinging around next iteration of loop. thread executing work item gets fair share of cpu , starts humming along , completes work item. signal call in work item runs , decrements our pending work item count 0 change state of countdownevent signalled. in meantime main thread wakes , goes through iterations of loop , hits wait call, since event got prematurely signalled pass on though there still pending work items.

again, avoiding subtle race condition easy when treat main thread work item. why countdownevent intialized 1 count , signal method called before wait.


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

html - Instapaper-like algorithm -

c# - How to execute a particular part of code asynchronously in a class -