3

HttpClient is not disposed or destroyed as it is reused between calls.

public async Task<HttpContent> DoSomething()
{
    var response = await _httpClient.PutAsync(url, content);

    return response.Content;
}

Does the response.Content need to be copied into another location and then the response which is a HttpContent manually disposed via .Dispose()? If so, why or why not?

NibblyPig
  • 51,118
  • 72
  • 200
  • 356
  • 3
    Possible duplicate of [Do HttpClient and HttpClientHandler have to be disposed?](http://stackoverflow.com/questions/15705092/do-httpclient-and-httpclienthandler-have-to-be-disposed) – Vivek Nuna Oct 27 '16 at 09:26

2 Answers2

2

The general rule is: always call Dispose on objects implementing IDisposable. The reason you always want to do that is because you never know if the implementation will ever need to dispose some resources.

As you can see in the source, it does dispose the actual stream, so you really should dispose it.

You might want to do it in the receiving method. There is no need to copy the result and call dispose right away.

You could call it like this, like you are used to do:

using (var r = await DoSomething())
{
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • Is it a stream though? As I'm not performing any operations on it that open a stream connection and start reading. I would have expected it to just read the entire lot, and that process to create and dispose the stream itself. Also, would calling dispose mean that my return statement returns `null`? – NibblyPig Oct 27 '16 at 09:29
  • As it does `if (_contentReadStream != null)` and I would have expected it to be null already by virtue of having read the entire content. – NibblyPig Oct 27 '16 at 09:38
  • If you have that intimate knowledge and you are sure the framework code will never change, it is save to leave it out. I'd better be safe though. – Patrick Hofman Oct 27 '16 at 09:40
  • 2
    Read http://stackoverflow.com/questions/15705092/do-httpclient-and-httpclienthandler-have-to-be-disposed , this is the wrong answer. – Nicholas Petersen Jan 12 '17 at 17:55
  • This question should be closed, first of all, as a duplicate. Anyways, maybe I'm wrong Patrick, but them I'm wrong with hundreds of others on SO. The answer to this already asked and answered question is: "The general consensus is that *you do not (should not) need to dispose of HttpClient*. Many people who are intimately involved in the way it works have stated this." I'm not saying this is a good design, it's not in my view. HttpClient should be used globally, I don't agree with that design, but it is what it is. – Nicholas Petersen Jan 12 '17 at 22:10
2

When I use the .net platform I always apply this rule: when an object implement the IDisposable interface soon as I finish to use the object I call Dispose().
For not forgetting call Dispose() I'm used to use the using statement

Tinwor
  • 7,765
  • 6
  • 35
  • 56