【发布时间】:2021-02-24 18:14:29
【问题描述】:
我正在拨打两个httpClient.GetAsync() 电话。
根据要求,两个调用之一将始终抛出 “No host known” 异常,一个将返回正确的 HttpResponseMessage 对象。
我的问题是在两个异步 httpClient 调用完成后仅确定布尔值。
public async Task<bool> BothHttpCallsTask(string hostName)
{
bool response1 = false;
bool response2 = false;
try
{
//httpClient and the GetAsync() are inside this method
response1 = await CheckRedirectionBool(url1);
response2 = await CheckRedirectionBool(url2);
}
catch(Exception e)
{
//when exception is caught here, the method evaluates as false
//as response2 is still not executed
}
return response1 || response2 ;
}
如何使执行仅在两个异步调用成功完成时才进行评估(请记住,强制异常使 return 语句在响应 2 可以从其执行中获取值之前进行评估) 如果两个 http 调用之一成功,我需要返回 true。
【问题讨论】:
-
你能简单地将每一个都包装在它自己的异常处理程序中吗?这样你就知道过去是哪一个等等。
-
我同意@JonH
-
哇,原来如此。感谢您的评论,我将其添加为答案
-
我在 CheckRedirectionBool 中确实有异常处理,但异常没有被捕获,仅在
BothHttpCallsTask -
为异步 http 调用放置 try catch 块的最佳做法是什么?如果您有任何资源,我将不胜感激被重定向到那里
标签: c# exception async-await dotnet-httpclient