I am trying to convert an application to use Tasks instead of Microsoft’s multithreaded framework, but I’m having trouble with the error handling. From Microsoft’s documentation ( http://msdn.microsoft.com/en-us/library/vstudio/0yd65esw.aspx ), I would expect the try-catch below to catch the exception:
private async void Button1_Click()
{
try
{
object obj = await TaskFunctionAsync()
}
catch(Exception ex)
{}
}
public Task<object> TaskFunctionAsync()
{
return Task.Run<object>(() =>
{
throw new Exception("foo");
return new object();
});
}
but when Button1_Click is fired, I get an unhandled exception within the lambda expression. Is there some way to get the exception out into the try-catch? I thought that this kind of error handling (so you don’t need to marshal from the task worker thread) was one of the major benefits of the Task framework.
I’ve also tried:
public async Task<object> TaskFunctionAsync()
{
return await Task.Run<object>(() =>
{
throw new Exception("foo");
return new object();
});
}
That’s not true. It is unhandled by user-code because the framework catches it, but not completely unhandled. Continue running the application to see that the exception will be caught by the catch in Button1_Click.