I
I
Igor Garbuz2021-03-08 19:25:45
.NET
Igor Garbuz, 2021-03-08 19:25:45

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);


2. Faulted will be here.
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);


UPD: Interestingly, in the first case, even if you do not pass a unit to the CancellationTokenSource constructor, it will still be Status = Canceled.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor Garbuz, 2021-03-10
@KinetonDev

Found the answer here .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question