gpt4 book ai didi

c# - 异步功能内的错误处理

转载 作者:行者123 更新时间:2023-12-03 07:50:23 25 4
gpt4 key购买 nike

我很难弄清楚如何正确处理异步函数中的异常。具有以下代码:

static async Task NotifyPartyAsync(Uri uri, string paramName, string paramValue)
{
string link = string.Format("{0}?{1}={2}", uri, paramName, HttpUtility.UrlEncode(paramValue));
using (var client = new HttpClient())
try {
using (HttpResponseMessage response = await client.GetAsync(link, HttpCompletionOption.ResponseHeadersRead))
logger.DebugFormat("HTTP {0} from {1}", (int)response.StatusCode, link);
}
catch (Exception ex) {
logger.Error(ex);
}
}

static void NotifyParty(Uri uri, string paramName, string paramValue)
{
string link = string.Format("{0}?{1}={2}", uri, paramName, HttpUtility.UrlEncode(paramValue));
using (var client = new HttpClient())
try {
using (HttpResponseMessage response = client.GetAsync(link, HttpCompletionOption.ResponseHeadersRead).Result)
logger.DebugFormat("HTTP {0} from {1}", (int)response.StatusCode, link);
}
catch (Exception ex) {
logger.Error(ex);
}
}

我如何重构它以不重复两个函数共有的99%代码?我需要同时和异步通知uri,除了要记录日志,我不在乎结果。

最佳答案

基本上,使用async/await可以遵循与同步编程相同的模式。除非绝对必要,否则不要在每个async方法中处理异常。在最顶层(即最外部的异步或同步方法)内处理它们。这个方法是什么取决于执行环境。

例如,如果是UI应用,则可能是async void事件处理程序:

async Task DoWorkAsync()
{
// don't handle exceptions here
}

async void Form_Load(object s, EventArgs args)
{
try {
await DoWorkAsync();
}
catch (Exception ex)
{
// log
logger.Error(ex);
// report
MessageBox.Show(ex.Message);
}
}

或者,它可能是控制台应用程序的 Main入口点:
static void Main(string[] args)
{
try {
DoWorkAsync().Wait();
}
catch (Exception ex)
{
// log
logger.Error(ex);
throw; // re-throw to terminate
}
}

您应该了解 async方法如何传播异常。检查 this了解更多详细信息。

另外,并非所有异常(exception)都相同,因此应平等对待。检查Eric Lippert的 "Vexing exceptions"

关于c# - 异步功能内的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22627548/

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