C# 异步/等待异常处理模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19148452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:14:51  来源:igfitidea点击:

async/await exception handling pattern

c#.netasync-await

提问by user1231595

I have the following reoccurring try/catch pattern in my code. Using a try/catch block to handle any exceptions thrown when calling a method in orionProxy.

我的代码中有以下重复出现的 try/catch 模式。使用 try/catch 块来处理调用 orionProxy 中的方法时抛出的任何异常。

async private void doGetContacts()
{
    try {
        currentContacts = await orionProxy.GetContacts (); // call method in orionProxy
        ShowContacts (); // do something after task is complete
    }
    catch (Exception e) {
        orionProxy.HandleException (e); // handle thrown exception
    }
}

What I would like to write is something like the following.

我想写的是如下内容。

async private void doGetContacts()
{
    currentContacts = await orionProxy.CheckForException(orionProxy.GetContacts ());
    ShowContacts (); // do something after task is complete but shouldn't run on exception
}

Any pointers/suggestions? I've tried various forms of Actions/Tasks/Lambdas but nothing will properly trap the exception in orionProxy.CheckForException(?) so ShowContacts doesn't run.

任何指示/建议?我已经尝试了各种形式的 Actions/Tasks/Lambdas,但没有任何东西可以正确地捕获 orionProxy.CheckForException(?) 中的异常,因此 ShowContacts 不会运行。

采纳答案by Stephen Cleary

I don't see why it wouldn't work, assuming GetContactsis an asyncmethod:

我不明白为什么它不起作用,假设GetContacts是一种async方法:

public async Task<T> CheckForExceptionAsync<T>(Task<T> source)
{
  try
  {
    return await source;
  }
  catch (Exception ex)
  {
    HandleException(ex);
    return default(T);
  }
}

On a side note, you should avoid async void(as I describe in my MSDN article) and end your asyncmethod names with the Asyncsuffix.

在一个侧面说明,你应该避免async void(正如我在MSDN文章介绍),并结束您async与方法名Async后缀