捕获由异步方法抛出的异常 [英] Catch an exception thrown by an async method

查看:187
本文介绍了捕获由异步方法抛出的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Microsoft for .NET中的async ctp,
是否可以捕获调用方法中异步方法抛出的异常?

Using the async ctp from Microsoft for .NET, is it possible to catch an exception thrown by an async method in the calling method?

public async void Foo()
{
    var x = await DoSomethingAsync();
    /* Handle the result, but sometimes an exception might be thrown
       For example, DoSomethingAsync get's 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
             when deployed the app will simply crash. */
    }
}

所以基本上我想要异步

推荐答案

有点奇怪,读取但是,异常会冒泡到调用代码 - 但它只会这样做如果您等待 Wait()调用 Foo

It's somewhat weird to read but yes, the exception will bubble up to the calling code - but it will only do so 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. */
    }
}

//or//

public void DoFoo()
{
    try
    {
        Foo().Wait();
    }
    catch (ProtocolException ex)
    {
          /* The exception will be caught because you've awaited the call. */
    }
} 

请注意,使用Wait()可能会导致应用程序阻止,如果.Net决定同步执行方法。

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

此说明 http://www.interact-sw.co.uk/iangblog/2010/11/01/csharp5-async-exceptions 相当不错 - 它讨论了编译器为实现这个魔法而采取的步骤。

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.

这篇关于捕获由异步方法抛出的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆