There are various ways in which to observe exceptions thrown within tasks. One of them is in a ContinueWith with OnlyOnFaulted:
var task = Task.Factory.StartNew(() =>
{
// Throws an exception
// (possibly from within another task spawned from within this task)
});
var failureTask = task.ContinueWith((t) =>
{
// Flatten and loop (since there could have been multiple tasks)
foreach (var ex in t.Exception.Flatten().InnerExceptions)
Console.WriteLine(ex.Message);
}, TaskContinuationOptions.OnlyOnFaulted);
My question: Do the exceptions become automatically observed once failureTask begins or do they only become observed once I 'touch' ex.Message?
Exceptions are propagated when you use one of the static or instance Task. Wait methods, and you handle them by enclosing the call in a try / catch statement. If a task is the parent of attached child tasks, or if you are waiting on multiple tasks, multiple exceptions could be thrown.
When exceptions happen, all the exceptions are re-thrown by the calling thread. To do that they're wrapped inside AggregateException and returned to the caller. So when we await a task, we only get the first exception from a collection of exceptions that might exist on a task.
ContinueWith(Action<Task,Object>, Object, TaskScheduler)Creates a continuation that receives caller-supplied state information and executes asynchronously when the target Task completes.
The ContinueWith function is a method available on the task that allows executing code after the task has finished execution. In simple words it allows continuation. Things to note here is that ContinueWith also returns one Task. That means you can attach ContinueWith one task returned by this method.
They are viewed as observed once you access the Exception
property.
See also AggregateException.Handle
. You can use t.Exception.Handle
instead:
t.Exception.Handle(exception =>
{
Console.WriteLine(exception);
return true;
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With