Search code examples
c#exceptionasync-awaitdotnet-httpclient

Exception in asynchronous call messes up execution


I am making two httpClient.GetAsync() calls.

According to the requirement, one of two calls will always throw a "No host known" exception and one will return a proper HttpResponseMessage object.

My problem is determining the bool value only after both async httpClient calls finish.

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.


Solution

  • My problem is determining the bool value only after both async httpClient calls finish.

    If you want to treat an exception the same as returning false, then I recommend writing a little helper method:

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

    Then it becomes easier to use 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];
    }