码迷,mamicode.com
首页 > 移动开发 > 详细

exception disappear when forgot to await an async method

时间:2019-02-27 15:47:18      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:blank   The   got   not   exce   start   col   method   sdn   

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

 

exception disappear when forgot to await an async method

标签:blank   The   got   not   exce   start   col   method   sdn   

原文地址:https://www.cnblogs.com/chucklu/p/10444031.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!