I'm trying to deal with exceptions inside of tasks, so far I've looked at the following links:
https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/exception-handling-task-parallel-library
How to handle Task.Run Exception
If I am correct, they suggest that the following code would not cause a User-Unhandled Exception.
public async void TestMethod()
{
try
{
await Task.Run(() => { throw new Exception("Test Exception"); });
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
However, I am getting a User-Unhandled Exception. I want to handle the exception outside of the Task so I can avoid writing code for changing the UI from a different thread. What am I doing wrong?
Here is a printscreen of the exception:
To answer your original question, before you edited it, one of the features of await
is that it will "unwrap" not only the return value, but any exceptions too. So if you need to catch an exception, it will not be an AggregateException
like it would be if you used .Wait()
or .Result
.
That's a Good Thing™
Also, it looks like Visual Studio is configured to break on all exceptions, even handled ones. This is handy (I always keep VS set like that because sometimes weird things can happen when exceptions are caught and hidden), but you just have to be aware of it. You can press F5 or F10 to continue execution and it should continue into the catch
block.
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