Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancellation Token in await method

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?

like image 473
J. Lennon Avatar asked Oct 05 '22 17:10

J. Lennon


1 Answers

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);
}
like image 147
Stephen Cleary Avatar answered Oct 10 '22 03:10

Stephen Cleary