异常从不在异步方法(C#)中到达处理程序

编程入门 行业动态 更新时间:2024-10-12 05:46:05
本文介绍了异常从不在异步方法(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#)中到达处理程序

本文发布于:2023-11-27 09:39:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1637545.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:异常   程序   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!