为了账号安全,请及时绑定邮箱和手机立即绑定

捕获异步空方法引发的异常。

捕获异步空方法引发的异常。

拉风的咖菲猫 2019-07-22 19:00:12
捕获异步空方法引发的异常。使用Microsoft for.NET的异步CTP,是否有可能捕获调用方法中的异步方法引发的异常?public async void Foo(){     var x = await DoSomethingAsync();     /* Handle the result, but sometimes an exception might be thrown.        For example, DoSomethingAsync gets data from the network        and the data is invalid... a ProtocolException might be thrown. */}public void DoFoo(){     try     {         Foo();     }     catch (ProtocolException ex)     {           /* The exception will never be caught.              Instead when in debug mode, VS2010 will warn and continue.              The deployed the app will simply crash. */     }}因此,基本上,我希望异步代码中的异常出现在我的调用代码中,如果这是可能的话。
查看完整描述

3 回答

?
森林海

TA贡献2011条经验 获得超2个赞

未捕获异常的原因是foo()方法有一个空返回类型,因此当调用WAIT时,它只是返回。由于DoFoo()没有等待foo的完成,因此不能使用异常处理程序。

这打开了一个更简单的解决方案,如果您可以更改方法签名-ALTERFoo()以便它返回类型Task然后DoFoo()能,会,可以await Foo(),如本代码所示:

public async Task Foo() {
    var x = await DoSomethingThatThrows();}public async void DoFoo() {
    try {
        await Foo();
    } catch (ProtocolException ex) {
        // This will catch exceptions from DoSomethingThatThrows
    }}


查看完整回答
反对 回复 2019-07-22
  • 3 回答
  • 0 关注
  • 307 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信