0

This question already has an answer here:

I have a simplistic structure and I have a hard time understanding why it works (or does not work) how I think it should work.

Basically, there are two methods

private async void DoStuff()
{
    try {
        AuthenticationStuff();
    }catch(UnauthorizedAccessException){
        UI.Display("AMAGAD!");
    }
}

private async void AuthenticationStuff()
{
    var user = GetUser();
    if(user == null) throw new UnauthorizedAccessException();

    DoMoreAuthenticationStuff();
}

Now the problem is that the exception never reaches DoStuff() method's handler. My first instinct was that "hey, it's an async method, I have to await it", but I can't do that either as apparently async void is different from async Task<void>.

I am trying to understand what's going on in here. Why isn't the exception going to the handler, but instead the debugger breaks at "DoMoreAuthenticationStuff()" with an unhandeled exception error?

2 답변


2

Exceptions raised by an async void method go directly to the SynchronizationContext that was active at the time the method started. This is one of the reasons why you should avoid async void. I cover this and other reasons in my MSDN article Best Practices in Asynchronous Programming.

To catch exceptions like this, change your async void method to async Task and await the returned task.


  • Thank you, Stephen! That's exactly what I was looking for. And that article of yours was very insightful! - Muhwu

0

My first instinct was that "hey, it's an async method, I have to await it", but I can't do that either as apparently async void is different from async Task.

You can just say async Task MyMethod(). Then you can await its result to propagate the exception (and to wait for completion).

Also observe Stephen Cleary's answer for more details.

Linked


Related

Latest