Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...