coding style - Make multiple asynchronous calls and do something when they are completed -
I have participated in this problem in many problematic languages and I was just wondering what its best way is.
I have three method calls that are closed asynchronously. I have a callback, I want to do something when all three callbacks will be completed.
What is the best way to code this? I usually end up with all these public bool flags and as you call more the code becomes more complex.
After
Coming from C #, I would probably use it to create an array of objects ( To complete each task), and pass that array to WaitAll
. Threaded tasks will get each manual resetset object, and call the set
method when they are ready. Waiting will stop all
calling thread until all the tasks are completed. I will give a C # code example: Private Zero SpawnWorkers () {ManualResetEvent [] [ResetEvents = New [] {New ManualResetEvent (wrong), New ManualResetEvent (wrong)}; //, do not block workers from a separate thread so that // WaitAll calls the main thread ThreadPool.QueueUserWorkItem ((state) =>; {ThreadPool.QueueUserWorkItem (Worker1, resetEvents [0]); ThreadPool.QueueUserWorkItem (Worker2, resetEvents [1]; WaitHandle.WaitAll (resetEvents); this.BeginInvoke (AllTasksAreDone);}); } Private Zero AllTasksAreDone () {// OK, all is done, according to the Private Zero Worker1 (object state)}} {// work, and then wait thread ((ManualResetEvent state)) .set ( ); } Private zero worker 2 (object state) {// work, and then waiting thread (signaling to state (manual reset) state) .set (); }
Note that AllTasksAreDone
method will not execute on thread thread thread that was used to give workers eggs, and on main thread ... It seems that many other languages have similar structures.
Comments
Post a Comment