【问题标题】:async/wait: bubbleup exceptions?async/await:冒泡异常?
【发布时间】:2019-10-02 13:46:28
【问题描述】:

这与必须从网络上的服务器收集一些信息的程序有关。

问题:如何从 GetServerResponseAsync 和 Check 中获取异常以通过 CheckAsync 冒泡到主程序?

如图所示,它们没有。 ErrorHandler 永远不会被击中。

我的主程序:

....
try
{  
    Task.Run(() => CheckAsync()); 
    // bubble to here?
    ReadConfiguration();
}
catch (Exception ex)
{ 
  // gather and handle all exceptions here
  ErrorHandler.NotifyMe(new[] { "some message" }, ErrorType.Stop); // never gets hit
}

public async Task CheckAsync()
{ 
    await GetServerResponseAsync("slm_check"); // may throw exception
    ...
    if (.....)
        throw new Exception("...");
    ... 
}

public async Task GetServerResponseAsync(string command)
{
   ...   
   // client = HttpClient() 
   using (apacheResponse = await client.GetAsync(ServerUrl + "...."))
   {      
        if (....)
            throw new Exception("Internal web server error", new Exception("Maybe MySQL server is down"));
        using (HttpContent content = apacheResponse.Content)
        {           
            if ( ....)
                throw new Exception("error message");
        }
    }
}            

【问题讨论】:

  • await Task.Run(...) 甚至更好的await CheckAsync()
  • 你为什么在后台线程上调用CheckAsync?删除Task.Run。

标签: c# asynchronous exception


【解决方案1】:

如何从 GetServerResponseAsync 和 Check 中获取异常以通过 CheckAsync 冒泡到主程序?

使用await 使用您的任务,而不是忽略它们。

具体来说,这一行:

Task.Run(() => CheckAsync());

正在从Task.Run 方法返回Task,然后将其忽略。代码应该是awaiting,而不是忽略该任务:

await Task.Run(() => CheckAsync());

正如其他评论者所指出的那样,Task.Run 这里没有任何意义。如果您的操作是异步的,则它不需要也在后台线程上运行。通常。 :) 因此,如果您取出 Task.Run,您的代码将如下所示:

await CheckAsync();

这将正确传播异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-20
    • 2015-07-03
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    • 2015-02-10
    • 2017-07-04
    相关资源
    最近更新 更多