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);
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With