ProfK ProfK - 28 days ago 11
C# Question

In an awaited task, do you have to write your own code to react to a cancellation?

Apart from

cancelToken.ThrowIfCancellationRequested()
, I was under the impression that the C# async infrastructure will attempt to abort the task, and if the line quote here has been called, it will throw a
OperationCanceledException
before continuing with trying to abort the rest of the task.

Someone on another question is suggesting I have to write code myself, like a
while(true)
loop within I listen for a cancellation. As if all tasks are meant to run forever if not cancelled.

Please confirm that I don't have to "catch" the cancellationon the token, and that the runtime will handle that because the method is marked 'async'.

Answer

Cancellation in Managed Threads:

the .NET Framework uses a unified model for cooperative cancellation of asynchronous or long-running...

(My emphasis).

It's not the old, unreliable, yank the thread out from under running code that has no idea what happened model of Thread.Abort. The code has to be written to deal with cancellation at times at which it deems it safe for cancellation to occur. That does mean inspecting the cancellation token at those times or calling ThrowIfCancellationRequested, to respect the request for cancellation.


You don't have to write any additional code if your code passes the cancellation token onto another block of code, and it's that block of code that is time consuming and has been written to respect the cancellation token - when it throws the OperationCancelledException, that will suffice to end your operation as well, provided you don't try to catch or otherwise handle that exception.

Comments