I have run into this problem across multiple programming languages and I was just wondering what the best way to handle it is.
I have three method calls that fire off asynchronously. Each one has a callback. I want to do something only when all three callbacks have completed.
What is the best way to code this? I usually end up with all these public bool flags and as you add more calls the code gets more convoluted.
Coming from C#, I would probably use
WaitHandle.WaitAll. You can create an array ofManualResetEventobjects (one for each task to be completed), and pass that array toWaitAll. The threaded tasks will get one ManualResetEvent object each, and call theSetmethod when they are ready.WaitAllwill block the calling thread until all tasks are done. I’ll give a C# code example:Note that the
AllTasksAreDonemethod will execute on the thread pool thread that was used to spawn the workers, and not on the main thread… I assume that many other languages have similar constructs.