异常从不在异步方法(C#)中到达处理程序 [英] Exception never reaching the handler in async method (C#)
问题描述
我有一个简单的结构,我很难理解为什么它工作(或不工作)我认为它应该工作。
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.
基本上,有两种方法
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();
}
现在的问题是异常从不达到 DoStuff ()
方法的处理程序。我的第一个直觉是嘿,这是一个异步的方法,我必须等待它,但我不能这样做,因为显然async void与async不同 Task< void>
。
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>
.
我正在想了解这里发生了什么。为什么没有异常处理程序,但是调试器在DoMoreAuthenticationStuff()
中有一个未处理的异常错误?
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?
推荐答案
由 async void
方法引发的异常直接转到 SynchronizationContext
在方法开始时处于活动状态。这是为什么你应该避免 async void
的原因之一。我在MSDN文章异步编程中的最佳做法中介绍了这个和其他原因
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.
要捕获这样的异常,请将您的 async void
方法更改为 async Task
和 await
返回的任务。
To catch exceptions like this, change your async void
method to async Task
and await
the returned task.
这篇关于异常从不在异步方法(C#)中到达处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!