gpt4 book ai didi

c# - 异步/等待异常处理模式

转载 作者:IT王子 更新时间:2023-10-29 04:09:24 28 4
gpt4 key购买 nike

我的代码中有以下重复出现的 try/catch 模式。使用 try/catch block 来处理调用 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
}
}

我想写的是下面这样的东西。

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

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

最佳答案

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

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

附带说明,您应该 avoid async void (如我在 MSDN 文章中所述)和 end your async method names with the Async suffix .

关于c# - 异步/等待异常处理模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19148452/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com