When handling exceptions in TPL tasks I have come across two ways to handle exceptions. The first catches the exception within the task and returns it within the result like so:
var task = Task<Exception>.Factory.StartNew(
() =>
{
try
{
// Do Something
return null;
}
catch (System.Exception e)
{
return e;
}
});
task.ContinueWith(
r =>
{
if (r.Result != null)
{
// Handle Exception
}
});
The second is the one shown within the documentation and I guess the proper way to do things:
var task = Task.Factory.StartNew(
() =>
{
// Do Something
});
task.ContinueWith(
r =>
{
if (r.Exception != null)
{
// Handle Aggregate Exception
r.Exception.Handle(y => true);
}
});
I am wondering if there is anything wrong with the first approach? I have received 'unhandled aggregate exception' exceptions every now and again using this technique and was wondering how this can happen?
To clarify, I think the second pattern is the better one but I have a chunk of code which makes use of the first pattern and I am trying to find out if it needs re-factoring i.e. if it turns out that not all exceptions will be trapped.