Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faulted vs Canceled task status after CancellationToken.ThrowIfCancellationRequested

Usually I don't post a question with the answer, but this time I'd like to attract some attention to what I think might be an obscure yet common issue. It was triggered by this question, since then I reviewed my own old code and found some of it was affected by this, too.

The code below starts and awaits two tasks, task1 and task2, which are almost identical. task1 is only different from task2 in that it runs a never-ending loop. IMO, both cases are quite typical for some real-life scenarios performing CPU-bound work.

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication
{
    public class Program
    {
        static async Task TestAsync()
        {
            var ct = new CancellationTokenSource(millisecondsDelay: 1000);
            var token = ct.Token;

            // start task1
            var task1 = Task.Run(() =>
            {
                for (var i = 0; ; i++)
                {
                    Thread.Sleep(i); // simulate work item #i
                    token.ThrowIfCancellationRequested();
                }
            });

            // start task2
            var task2 = Task.Run(() =>
            {
                for (var i = 0; i < 1000; i++)
                {
                    Thread.Sleep(i); // simulate work item #i
                    token.ThrowIfCancellationRequested();
                }
            });  

            // await task1
            try
            {
                await task1;
            }
            catch (Exception ex)
            {
                Console.WriteLine(new { task = "task1", ex.Message, task1.Status });
            }

            // await task2
            try
            {
                await task2;
            }
            catch (Exception ex)
            {
                Console.WriteLine(new { task = "task2", ex.Message, task2.Status });
            }
        }

        public static void Main(string[] args)
        {
            TestAsync().Wait();
            Console.WriteLine("Enter to exit...");
            Console.ReadLine();
        }
    }
}

The fiddle is here. The output:

{ task = task1, Message = The operation was canceled., Status = Canceled }
{ task = task2, Message = The operation was canceled., Status = Faulted }

Why the status of task1 is Cancelled, but the status of task2 is Faulted? Note, in both cases I do not pass token as the 2nd parameter to Task.Run.

like image 456
noseratio Avatar asked Jun 23 '14 06:06

noseratio


People also ask

What is the way to create a task that can be Cancelled after it starts?

Create and start a cancelable task. Pass a cancellation token to your user delegate and optionally to the task instance. Notice and respond to the cancellation request in your user delegate. Optionally notice on the calling thread that the task was canceled.

What is task Cancelled exception?

There's 2 likely reasons that a TaskCanceledException would be thrown: Something called Cancel() on the CancellationTokenSource associated with the cancellation token before the task completed. The request timed out, i.e. didn't complete within the timespan you specified on HttpClient. Timeout .

Which method can you use to cancel an ongoing operation that uses CancellationToken?

The CancellationToken is used in asynchronous task. The CancellationTokenSource token is used to signal that the Task should cancel itself. In the above case, the operation will just end when cancellation is requested via Cancel() method.

Which object do you inspect to determine if a long running task will be Cancelled?

For canceling, we use CancellationTokenSource object.


1 Answers

There are two problems here. First, it's always a good idea to pass CancellationToken to the Task.Run API, besides making it available to the task's lambda. Doing so associates the token with the task and is vital for the correct propagation of the cancellation triggered by token.ThrowIfCancellationRequested.

This however doesn't explain why the cancellation status for task1 still gets propagated correctly (task1.Status == TaskStatus.Canceled), while it doesn't for task2 (task2.Status == TaskStatus.Faulted).

Now, this might be one of those very rare cases where the clever C# type inference logic can play against the developer's will. It's discussed in great details here and here. To sum up, in case with task1, the following override of Task.Run is inferred by compiler:

public static Task Run(Func<Task> function)

rather than:

public static Task Run(Action action)

That's because the task1 lambda has no natural code path out of the for loop, so it may as well be a Func<Task> lambda, despite it is not async and it doesn't return anything. This is the option that compiler favors more than Action. Then, the use of such override of Task.Run is equivalent to this:

var task1 = Task.Factory.StartNew(new Func<Task>(() =>
{
    for (var i = 0; ; i++)
    {
        Thread.Sleep(i); // simulate work item #i
        token.ThrowIfCancellationRequested();
    }
})).Unwrap();

A nested task of type Task<Task> is returned by Task.Factory.StartNew, which gets unwrapped to Task by Unwrap(). Task.Run is smart enough to do such unwrapping automatically for when it accepts Func<Task>. The unwrapped promise-style task correctly propagates the cancellation status from its inner task, thrown as an OperationCanceledException exception by the Func<Task> lambda. This doesn't happen for task2, which accepts an Action lambda and doesn't create any inner tasks. The cancellation doesn't get propagated for task2, because token has not been associated with task2 via Task.Run.

In the end, this may be a desired behavior for task1 (certainly not for task2), but we don't want to create nested tasks behind the scene in either case. Moreover, this behavior for task1 may easily get broken by introducing a conditional break out of the for loop.

The correct code for task1 should be this:

var task1 = Task.Run(new Action(() =>
{
    for (var i = 0; ; i++)
    {
        Thread.Sleep(i); // simulate work item #i
        token.ThrowIfCancellationRequested();
    }
}), token);
like image 55
noseratio Avatar answered Sep 22 '22 09:09

noseratio