如何等待多个异步操作完成

wal*_*ter 7 .net c#

我正在寻找一种简单的方法来调用多个异步操作,并具有取消它们的能力:

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

我如何构建StartAsyncBatch?它应该是派生类

class StartAsyncBatch : IAsyncResult
Run Code Online (Sandbox Code Playgroud)

Che*_*hen 8

简短的回答是您可以通过CancellationTokenSource构建的相应CancellationToken取消等待任务.这是一个例子.

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 e.g. a cancel button click event you call tokenSource.Cancel()
Run Code Online (Sandbox Code Playgroud)

当你处理一些任务时,情况会有所不同.首先,你需要知道取消任务的时间,其他任务会继续吗?如果是,您需要为不同的任务创建不同的取消令牌并独立处理取消.否则,他们可以共享相同的取消令牌.不同的要求导致不同的取消处理政策