exception disappear when forgot to await an async method

本文详细探讨了在C#中使用async/await时的异常处理机制。解释了当调用async方法未使用await时,异常如何被忽略,以及如何通过await或Wait()正确捕获这些异常。同时提醒开发者注意使用Wait()可能引起的程序阻塞问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://github.com/aspnet/AspNetWebStack/issues/235

https://stackoverflow.com/questions/5383310/catch-an-exception-thrown-by-an-async-void-method

 

如果异常发生在1个async方法中,而调用这个方法的地方,没有做await。那么异常就会消失。

It's somewhat weird to read but yes, the exception will bubble up to the calling code - but only if you await or Wait() the call to Foo.

public async void DoFoo() { try { await Foo(); } catch (ProtocolException ex) { // The exception will be caught because you've awaited // the call in an async method. } } //or// public void DoFoo() { try { Foo().Wait(); } catch (ProtocolException ex) { /* The exception will be caught because you've waited for the completion of the call. */ } }

Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started. - https://msdn.microsoft.com/en-us/magazine/jj991977.aspx

Note that using Wait() may cause your application to block, if .Net decides to execute your method synchronously.

This explanation http://www.interact-sw.co.uk/iangblog/2010/11/01/csharp5-async-exceptions is pretty good - it discusses the steps the compiler takes to achieve this magic.

 

Async/Await - Best Practices in Asynchronous Programming

 

转载于:https://www.cnblogs.com/chucklu/p/10444031.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值