Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpResponseMessage do you dispose it?

Whilst waiting for the new shiny HttpClientFactory addressing all the issues of HttpClient,

I still cannot find an answer whether HttpResponseMessage and HttpRequestMessage should be disposed.

Is something like below a good practice?

Do you use a Using statement with HttpResponseMessage?

//httpClient has been injected

using (HttpResponseMessage messageResponse = await httpClient.GetAsync(uri, cancellationToken).ConfigureAwait(false))
{
    using (HttpContent content = messageResponse.Content)
    {
        if (messageResponse.IsSuccessStatusCode)
        {
            var json  = await content.ReadAsStringAsync();
            var response = await Task.Run(() => JsonConvert.DeserializeObject<TResponse>(json, serializerSettings));

            return new MyWrapperResponse<TResponse>(messageResponse,response);
        }
    }
}
like image 295
developer9969 Avatar asked Nov 07 '22 06:11

developer9969


1 Answers

Do you use a Using statement with HttpResponseMessage?

Short Answer: Yes you can.

Is something like below a good practice?

It depends.

While it is usually advised practice to wrap IDisposable derived classes with using for proper disposal, the example shown may be using it incorrectly.

The messageResponse is being injected into a wrapper class (MyWrapperResponse) and then the function returns immediately after. If the response message is being used outside of that wrapper's constructor, it is possible that the response would have already been disposed.

like image 198
Nkosi Avatar answered Nov 26 '22 06:11

Nkosi