Cancellation Token in await method

情到浓时终转凉″ 提交于 2019-12-19 07:45:12

问题


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

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();
}

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?


回答1:


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);
}


来源:https://stackoverflow.com/questions/13822726/cancellation-token-in-await-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!