简体   繁体   English

异步调用中的异常会扰乱执行

[英]Exception in asynchronous call messes up execution

I am making two httpClient.GetAsync() calls.我正在进行两个httpClient.GetAsync()调用。

According to the requirement, one of two calls will always throw a "No host known" exception and one will return a proper HttpResponseMessage object.根据要求,两个调用之一将始终抛出“No host known”异常,一个将返回正确的HttpResponseMessage object。

My problem is determining the bool value only after both async httpClient calls finish.我的问题是只有在两个异步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 ;
}

How do I make the execution only evaluate when both async calls complete successfully (keeping in mind the mandatory exception makes the return statement evaluate before response 2 can get a value from its execution) I need to return true if even one of the two http calls are successful.如何使执行仅在两个异步调用成功完成时进行评估(请记住,强制异常使返回语句在响应 2 可以从其执行中获取值之前进行评估)如果即使是两个 http 调用之一,我也需要返回 true是成功的。

Could you simply wrap each in its own exception handler?你能简单地将每个包装在它自己的异常处理程序中吗? For instance:例如:

try{
 response1 = ...
}
catch(Exception e){
 //set some flag here
}

try{
 response2 = ...
}
catch(Exception e){
 //set some flag here
}

This way you know which one past vs which one didn't and set some flags based on that condition, etc.通过这种方式,您可以知道哪一个过去与哪一个没有,并根据该条件设置一些标志,等等。

My problem is determining the bool value only after both async httpClient calls finish.我的问题是只有在两个异步 httpClient 调用完成后才确定布尔值。

If you want to treat an exception the same as returning false , then I recommend writing a little helper method:如果您想将异常视为与返回false相同,那么我建议编写一个小辅助方法:

async Task<bool> TreatExceptionsAsFalse(Func<Task<bool>> action)
{
  try { return await action(); }
  catch { return false; }
}

Then it becomes easier to use Task.WhenAll :然后使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM