如何等待多个异步操作完成 [英] How to wait on multiple asynchronous operation completion

查看:226
本文介绍了如何等待多个异步操作完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要寻找致电与取消它们的能力异步操作的一个简单的方法:

  VAR cancelTask​​ =新的ManualResetEvent(假);
IAsyncResult的AR = StartAsyncBatch(cancelTask​​);
INT RESP = WaitHandler.WaitAny({ar.AsyncWaitHandle,cancelTask​​});
 

我怎么也得建StartAsyncBatch?它应该被派生类

 类StartAsyncBatch:IAsyncResult的
 

解决方案

简要的回答是,你可以通过相应的CancellationToken由CancellationTokenSource建成取消等待任务。下面是一个例子。

  VAR tokenSource =新CancellationTokenSource();

VAR任务= Task.Factory.StartNew(()=>
{
    的for(int i = 0;我小于10;我++)
    {
        如果(tokenSource.IsCancellationRequested)
        {
            //你知道该任务将被取消
            //做些什么来停止任务
            //或者你可以使用tokenSource.Token.ThrowIfCancellationRequested()
            //控制流量
        }
        其他
        {
            //工作步骤i
        }
    }
},tokenSource.Token);

尝试
{
    task.Wait(tokenSource.Token);
}
赶上(OperationCanceledException cancelEx)
{
    //回滚或东西
}

//地方如取消按钮点击事件调用tokenSource.Cancel()
 

事情是有点不同的,当你正在处理几个任务。首先你需要知道的取消任务时,将其他任务继续下去吗?如果是的话,你需要创建不同的取消标记为不同的任务和独立处理的取消。否则它们可以共享相同的取消标记。不同的需求导致不同的取消处理策略。

I am looking for a simple way of calling multiple asynchronous operation with ability to cancel them:

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

How I have to build StartAsyncBatch? Should it be derived class

class StartAsyncBatch : IAsyncResult

解决方案

The brief answer is you can cancel the waiting tasks via corresponding CancellationToken built by 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 e.g. a cancel button click event you call tokenSource.Cancel()

Things are a little different when you are dealing with a few tasks. Firstly you need to know when cancelling a task, will other tasks continue? If yes, you need to create different cancellation tokens for different tasks and handle the cancellation independently. Otherwise they can share the same cancellation token. Different requirement causes different cancellation handling policy.

这篇关于如何等待多个异步操作完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆