异步/计谋异常处理模式 [英] async/await exception handling pattern
问题描述
我在code以下反复出现的try / catch模式。使用try / catch块来处理调用orionProxy的方法时抛出的异常。
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.
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
}
任何指针/建议吗?我已经试过各种形式的操作/任务/ lambda表达式,但什么都不会正确地捕获异常orionProxy.CheckForException(?),所以ShowContacts不运行。
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.
推荐答案
我不明白为什么这是行不通的,假设 GetContacts
是异步
方法:
I don't see why it wouldn't work, assuming GetContacts
is an async
method:
public async Task<T> CheckForExceptionAsync<T>(Task<T> source)
{
try
{
return await source;
}
catch (Exception ex)
{
HandleException(ex);
return default(T);
}
}
在一个侧面说明,您应该避免异步无效
(如我描述我在MSDN文章)和结束你的异步
与异步
后缀的方法名。
On a side note, you should avoid async void
(as I describe in my MSDN article) and end your async
method names with the Async
suffix.
这篇关于异步/计谋异常处理模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!