Exception never reaching the handler in async meth

2019-08-16 02:29发布

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楼-- · 2019-08-16 03:14

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.

查看更多
仙女界的扛把子
3楼-- · 2019-08-16 03:16

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.

查看更多
登录 后发表回答