dath
dath

Reputation: 915

Handling Exceptions Inside Task.Run

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:

enter image description here

Upvotes: 4

Views: 4452

Answers (1)

Gabriel Luci
Gabriel Luci

Reputation: 40868

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.

Upvotes: 4

Related Questions