问题描述
有很多理由把令牌任务,这里提到的构造函数:
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);
}
这篇关于取消标记在等待的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!