[英]Exception in asynchronous call messes up execution
我正在進行兩個httpClient.GetAsync()
調用。
根據要求,兩個調用之一將始終拋出“No host known”異常,一個將返回正確的HttpResponseMessage
object。
我的問題是只有在兩個異步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 ;
}
如何使執行僅在兩個異步調用成功完成時進行評估(請記住,強制異常使返回語句在響應 2 可以從其執行中獲取值之前進行評估)如果即使是兩個 http 調用之一,我也需要返回 true是成功的。
你能簡單地將每個包裝在它自己的異常處理程序中嗎? 例如:
try{
response1 = ...
}
catch(Exception e){
//set some flag here
}
try{
response2 = ...
}
catch(Exception e){
//set some flag here
}
通過這種方式,您可以知道哪一個過去與哪一個沒有,並根據該條件設置一些標志,等等。
我的問題是只有在兩個異步 httpClient 調用完成后才確定布爾值。
如果您想將異常視為與返回false
相同,那么我建議編寫一個小輔助方法:
async Task<bool> TreatExceptionsAsFalse(Func<Task<bool>> action)
{
try { return await action(); }
catch { return false; }
}
然后使用Task.WhenAll
變得更容易:
public async Task<bool> BothHttpCallsTask(string hostName)
{
var results = await Task.WhenAll(
TreatExceptionsAsFalse(() => CheckRedirectionBool(url1)),
TreatExceptionsAsFalse(() => CheckRedirectionBool(url2))
);
return results[0] || results[1];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.