Why do we have 2 different results in next 2 scenarios? In these samples token.IsCancellationRequested = true. Why does functionality have changed if i comment if(token.IsCancellationRequested), when in fact we can type if(true) instead of it.
Somewhere i read that in order to have TaskCanceledException ( Status = Canceled ) we need to follow next 3 conditions:
- Throw OperationCanceledException and pass token to it's constructor
- Pass the same token to the method, which creates a task (Task.Run)
- IsCancellationRequested should be true.
And it's true, if we use if(token.IsCancellationRequested) throw new OperationCanceledException(token) (equals to token.ThrowIfCancellationRequested) (second scenario) , we need to follow 2 other contidionts, but in first scenario if we comment if(token.IsCancellationRequested) (we can even remove 1 from CTS constructor ) we will still get Canceled status.
1. Here Status is Canceled
CancellationTokenSource cts = new CancellationTokenSource(1);
var token = cts.Token;
var task = Task.Run(() =>
{
Thread.Sleep(5);
// if(token.IsCancellationRequested)
throw new OperationCanceledException(token);
});
Thread.Sleep(50);
Console.WriteLine(task.Status);
2. Here - Faulted.
CancellationTokenSource cts = new CancellationTokenSource(1);
var token = cts.Token;
var task = Task.Run(() =>
{
Thread.Sleep(5);
if(token.IsCancellationRequested) // true
throw new OperationCanceledException(token);
});
Thread.Sleep(50);
Console.WriteLine(task.Status);