取消标记在等待的方法 [英] Cancellation Token in await method

查看:210
本文介绍了取消标记在等待的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多理由把令牌任务,这里提到的构造函数:
<一href=\"http://stackoverflow.com/questions/3712939/cancellation-token-in-task-constructor-why\">Cancellation令牌任务的构造函数:为什么

There are many reasons to put a token in the constructor of a task, mentioned here: Cancellation token in Task constructor: why?

通过使用关键字,异步/的await,如何实现这工作吗?
例如我的code以下:

With the use of keywords, async / await, how is that working? for example my code below:

public async Task MethodAsync(CancellationToken token)
{
  await Method01Async();
  await Method02Async();
}

虽然它是一个异步过程。在任何时候,我用Task.StartNext或Task.Run或新建任务。为了能够指定我取消标记,我该怎么办?

Although it is an asynchronous process. In no time I used "Task.StartNext" or "Task.Run" or "new Task". To be able to specify my cancellation token, how can I do?

推荐答案

您不应该使用工作构造函数异步方法。通常情况下,你只是想通过的CancellationToken 对,是这样的:

You aren't supposed to use the Task constructor in async methods. Usually, you just want to pass the CancellationToken on, like this:

public async Task MethodAsync(CancellationToken token)
{
  await Method01Async(token);
  await Method02Async(token);
}

这篇关于取消标记在等待的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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