Reading Task-based Asynchronous Pattern by Stephen Toub I'm trying to see how cancellation works for tasks. In the section Consuming the Task-based Asynchronous Pattern under Await, in 3-rd paragraph it says:
If the Task or Task TResult> awaited ended in the Canceled state, an OperationCanceledException will be thrown.
I'm trying to see this in action in the code below.
static void Main(string[] args)
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken cancellationToken = cancellationTokenSource.Token;
Task<int> valueTask = DoStuffAsync(cancellationToken);
Thread.Sleep(TimeSpan.FromSeconds(1));
cancellationTokenSource.Cancel();
Console.WriteLine("value task's status: {0}", valueTask.Status);
Console.ReadLine();
}
And the DoStuffAsync() method
static async Task<int> DoStuffAsync(CancellationToken cancellationToken)
{
await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken);
return 42;
}
Executing this code doesn't throw any exception, it just prints:
value task's status: Cancelled
Now, my expectation was in DoStuffAsync() method since await Task.Delay(...) is cancelled, we have awaited task ended in Canceled state, hence exception should have been thrown (according to quote from the TAP document), but if I put a breakpoint on Console.ReadLine() and check valueTask it's Status is Cancelled, and Exception is null.
Can anybody help me understand if I misread the document, or code I come up with is not properly reproducing the case?
Task.Exceptionwould have an exception, that's just silly :) You have to understand that you have two separate threads of execution here, and you never synchronize them - where exactly would you expect the exception to happen? On the thread pool, killing your entire application? - Luaan