3

Suppose I have an array of tasks say taskArray and I create a task continuation using ContinueWhenAll and one or more of the tasks in taskArray throw some exception. My question is, is there any scenario where this may lead to an UnobservedTaskException?

So basically the question boils down to, does ContinueWhenAll observe the exceptions in taskArray like Wait would do for a single task? If no, then what should be used for a group of tasks if I don't want to look explicitly at the exceptions on each task. I don't want to use WaitAll as it is not available for generic tasks.

Dave New
  • 38,496
  • 59
  • 215
  • 394
Anupam
  • 870
  • 4
  • 9
  • 19

2 Answers2

2

davenewza's answer suffices if catching the exceptions from tasks application wide is acceptable.

If not then you have to do what you don't want to do (observe the exception in some way). You have two options:

  1. Create a continuation for each task that runs in the OnlyOnFaulted case whose only job is to observe the exception by looking at the Exception property on the task.
  2. In your continuation for ContinueWhenAll, you can split the tasks into those with exceptions and those without:

        Task.Factory.ContinueWhenAll(tasks, ts =>
        {
            var lookup = ts.ToLookup(t => t.Exception != null);
            var faultedTasks = lookup[true];
            var nonFaultedTasks = lookup[false];
        });
    
Matt Smith
  • 17,026
  • 7
  • 53
  • 103
1

No, ContinueWhenAll will not observe any exceptions thrown from within your tasks.

You can "catch" and observe any exceptions that could have occurred in any of your tasks using the TaskScheduler.UnobservedTaskException event. This fires just before an UnobservedTaskException is thrown by the finalizer thread. Here you can observe the exceptions.

TaskScheduler.UnobservedTaskException += (sender, e) =>
{
    e.SetObserved();
};
Dave New
  • 38,496
  • 59
  • 215
  • 394
  • The ContinueWhenAny will only execute on the *first* task to finish(according to the documentation/example on msdn: http://msdn.microsoft.com/en-us/library/dd321530.aspx, and notice that it returns only a single task, not an array of tasks), so it is not a good solution for this. – Matt Smith Nov 30 '12 at 14:10
  • Very true! I have updated my answer. TaskScheduler.UnobservedTaskException is the preferred solution. – Dave New Nov 30 '12 at 14:14
  • Thanks! It was useful, I ended up using Matt's method so I marked it as the answer. – Anupam Nov 30 '12 at 18:31