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?
Exceptions raised by an
async void
method go directly to theSynchronizationContext
that was active at the time the method started. This is one of the reasons why you should avoidasync 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 toasync Task
andawait
the returned 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.