7

I've been trying to figure out why I'm getting a TaskCanceledException for a bit of async code that has recently started misbehaving. I've reduced my issue down to a small code snippet that has me scratching my head:

static void Main(string[] args)
{
    RunTest();
}

private static void RunTest()
{
    Task.Delay(1000).ContinueWith(t => Console.WriteLine("{0}", t.Exception), TaskContinuationOptions.OnlyOnFaulted).Wait();
}

As far as I'm aware, this should simply pause for a second and then close. The ContinueWith won't be called (this only applies to my actual use-case). However, instead I'm getting a TaskCanceledException and I've no idea where that is coming from!

Barguast
  • 5,482
  • 7
  • 39
  • 69
  • It is related to your taskcontinuationoptions if you change it to none it works. – Philip Stuyck Feb 20 '15 at 16:44
  • 8
    The continuation task returned from `ContinueWith` is cancelled because the parent task didn't fault. You need to separate the parent and continuation tasks in this case and wait for the parent. – Lee Feb 20 '15 at 16:45

2 Answers2

2

You are using the wrong taskcontinuationoption:

See following link : https://msdn.microsoft.com/en-us/library/system.threading.tasks.taskcontinuationoptions%28v=vs.110%29.aspx

It says : Specifies that the continuation task should be scheduled only if its antecedent threw an unhandled exception. This option is not valid for multi-task continuations.

Philip Stuyck
  • 7,131
  • 3
  • 26
  • 38
2

As guys said above this call requires just antecedent-task in faulted-status otherwise will throw TaskCanceledException, for this concrete case you can generalize ContinueWith to process all statuses:

await Task.Delay(1000).ContinueWith(
    task => 
        {
            /* take into account that Canceled-task throw on next row the TaskCancelledException */

            if (!task.IsFaulted) {
                return;
            }

            Console.WriteLine("{0}", task.Exception);
            // do smth like 'throw task.Exception.InnerException'
        });
vladimir
  • 11,406
  • 2
  • 30
  • 53