Search code examples
c#dotnet-httpclient

Is it necessary to call Dispose when IsSuccessStatusCode returns false?


Basically I'm wondering if calling Dispose is necessary when IsSuccessStatusCode returns false after calling something like HttpClient.PostAsync, I'm using a static HttpClient so I can't use a using block

HttpResponseMessage response = await Global.HttpClient.PostAsync("*****", content);
if (response.IsSuccessStatusCode)
{
    // Get data from the response
    response.Dispose();
}
else
{
    // Log error
}
            
return results;

I'm wondering if this is the correct way to do it


Solution

  • The need to dispose of the response is not (necessarily) related to the value of its status code. So you should do that regardless.

    An alternative to using would be a try/finally:

    HttpResponseMessage response = await Global.HttpClient.PostAsync("*****", content);
    try
    {
        if (response.IsSuccessStatusCode)
        {
            // Get data from the response
        }
        else
        {
            // Log error
        }
    }
    finally
    {
        response?.Dispose();
    }
                
    return results;
    

    But that should only be the equivalent code of using a using. So, I'd actually recommend that. And I do not see a reason why that should not be possible, here.

    using var response = await Global.HttpClient.PostAsync("*****", content);
    
    if (response.IsSuccessStatusCode)
    {
        // Get data from the response
    }
    else
    {
        // Log error
    }
    
    return results;
    

    Mind that this would dispose of the response instance, not the static HttpClient.