5

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?

Community
  • 1
  • 1
J. Lennon
  • 3,311
  • 4
  • 33
  • 64
  • refactor those methods to take a `CancellationToken`. – CodesInChaos Dec 11 '12 at 15:18
  • how can I refactor if I do not create a task (explicitly)? – J. Lennon Dec 11 '12 at 15:29
  • If you can't change `Method01Async` to accept a token, the best you can do really is check the token yourself after `01` has completed, and exit early rather than calling `02` – Damien_The_Unbeliever Dec 11 '12 at 15:31
  • 1
    [Here](http://blogs.msdn.com/b/pfxteam/archive/2012/10/05/how-do-i-cancel-non-cancelable-async-operations.aspx?PageIndex=1) is a great article on the subject. Do you want to actually stop the async task, or just continue on if the token is canceled and stop waiting? Are you aware of the potential pitfalls of doing so? – Servy Dec 11 '12 at 15:36

1 Answers1

4

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);
}
Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • If I can not. Then always have to check the token inside the asynchronous method? – J. Lennon Dec 11 '12 at 15:42
  • @J.Lennon: You do get the benefits, actually. If you check it right away, then the rest of your code won't run. When it's cancelled, the `Task` returned from `MethodAsync` will complete in a cancelled state. You get all the benefits that you would get if you passed it to a `Task` constructor. – Stephen Cleary Dec 11 '12 at 16:10