Answer the question
In order to leave comments, you need to log in
Task.Run and CancellationToken. How does cancellation work in this case?
Hello. Why will the task end up with a different status in the following two cases? Considering that
token.IsCancellationRequested = true. Why does the functionality change if, in fact, the equivalent of if (true) is written there?
1. Here Status = 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);
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);
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question