通过捕捉一个异步方法抛出的异常 [英] Catch an exception thrown by an async method

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

问题描述

使用异步CTP从Microsoft .NET,
是否有可能捕获由异步方法中调用的方法抛出的异常?

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. */
    }
}

所以基本上我想从异步code冒泡异常的情况,我调用code
如果这是甚至可能在所有的

So basically I want the exception from the async code to bubble up in to my calling code if that is even possible at all.

推荐答案

这有点怪异阅读(一记滚泥是如何我发现它!),但肯定的,异常会冒泡到调用$ C $ç - 但它只会做这样的如果您的await 等待()调用

It's somewhat weird to read (a mind f*** is how I'm finding it!) 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()的可能会导致应用程序阻止,如果净决定同步执行你的方法。

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

这说明<一个href=\"http://www.interact-sw.co.uk/iangblog/2010/11/01/csharp5-async-exceptions\">http://www.interact-sw.co.uk/iangblog/2010/11/01/csharp5-async-exceptions为pretty好 - 它讨论了编译器会实现这一神奇的步骤

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天全站免登陆