Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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();
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top