gpt4 book ai didi

c# - 如何捕获 async void 方法异常?

转载 作者:行者123 更新时间:2023-11-30 21:43:24 25 4
gpt4 key购买 nike

我有一个这样的实现:

Task<IEnumerable<Item1>> GetItems1() 
{
return RunRequest(async () => ParseItemsFromResponse(await(httpClient.Get(..))));
}

Task<IEnumerable<Item2>> GetItems2()
{
return RunRequest(async () => ParseItemsFromResponse(await httpClient.Get(..)));
}


TResult RunRequest<TResult>(Func<TResult> req)
{
try
{
return req();
}
catch (Exception ex)
{
// Parse exception here and throw custom exceptions
}
}

问题是 void 匿名方法 async () => ParseItemsFromResponse(..)

因为它返回 void 而不是 Task,如果在匿名方法中抛出异常,它实际上不会被 try 捕获在 RunRequest 中捕获

有什么关于如何重构它的建议吗?

最佳答案

RunRequest应该采取 Func<Task<TResult>> ,因此:

async Task<TResult> RunRequestAsync<TResult>(Func<Task<TResult>> req)
{
try
{
return await req().ConfigureAwait(false);
}
catch (Exception ex)
{
// Parse exception here and throw custom exceptions
}
}

然后是你的async lambda 转换为 async Task<T>方法而不是 async void .

我有关于 sync/async delegates 的更多信息在我的博客上。

关于c# - 如何捕获 async void 方法异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41742853/

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