How to wait for the completion of several asynchronous operations

I am looking for an easy way to call multiple asynchronous operations with the ability to cancel them:

var cancelTask = new ManualResetEvent(false); IAsyncResult ar = StartAsyncBatch(cancelTask); int resp = WaitHandler.WaitAny({ar.AsyncWaitHandle, cancelTask}); 

How do I create StartAsyncBatch? If it is a derived class

 class StartAsyncBatch : IAsyncResult 
+7
source share
3 answers

Short answer: you can cancel waiting tasks through the corresponding CancellationToken created by the CancellationTokenSource. Here is an example.

 var tokenSource = new CancellationTokenSource(); var task = Task.Factory.StartNew(() => { for (int i = 0; i < 10; i++) { if (tokenSource.IsCancellationRequested) { //you know the task is cancelled //do something to stop the task //or you can use tokenSource.Token.ThrowIfCancellationRequested() //to control the flow } else { //working on step i } } }, tokenSource.Token); try { task.Wait(tokenSource.Token); } catch (OperationCanceledException cancelEx) { //roll back or something } //somewhere eg a cancel button click event you call tokenSource.Cancel() 

Everything is a little different when you are dealing with several tasks. First, you need to know when you cancel a task, will other tasks be performed? If so, you need to create different undo markers for different tasks and adjust the undo yourself. Otherwise, they can use the same cancellation token. Different requirements lead to different cancellation processing policies.

+8
source

If you are using .NET 3.5 or 4.0, I would recommend using a parallel task library (TPL). It is much easier to control your tasks, and you have much more flexibility in controlling / canceling tasks. Check out this link. Parallelism task If you use TPL and you need to cancel all or any tasks that you need to create a CancellationToken example on how to do this Cancel a task .

And yes, you can use TPL in .NET 3.5. Here is a link on how to do this Reactive Extensions and Parallel Extensions Basically you will need to install Reactive Extensions (Rx)

+2
source

Danny's code is logically correct, but actually does not work. When WaitHandle.WaitAll () is called, the program blocks (including two tasks). You can create a new thread to wait for all events that will be signaled:

 Thread t = new Thread(() => { WaitHandle.WaitAll(handles); MessageBox.Show("Both Threads are finished"); }); t.Start(); 
0
source

All Articles