Exception never reaching the handler in async method (C#) [duplicate]

我与影子孤独终老i 提交于 2019-12-12 04:49:27

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/17923204/exception-never-reaching-the-handler-in-async-method-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!