1

I've got a need to store a disposable object as a class member. This is HttpClient which is disposable and I can either dispose it manually or put it into using(var client=new ....). Now imagine such situation:

public class Session
{
    private HttpClient m_httpClient;

    public Session()
    {
       m_httpClient = new HttpClient();
    }
}

How do I dispose HttpClient? Does the garbage collector when deleting session takes care of disposable HttpClient also ? There are destructors in C++. In C# it's not neccessary. Should I make session object disposable too then? Thank you.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Konrad
  • 6,385
  • 12
  • 53
  • 96
  • you can use `using()` for such situation – Mohit S Sep 28 '15 at 09:27
  • 2
    Typically if you have a resource which needs disposing as an instance field, your class should implement `IDisposable` too, and call `Dispose` on the field when the container is disposed. – Jon Skeet Sep 28 '15 at 09:29
  • See this : http://stackoverflow.com/questions/15705092/do-httpclient-and-httpclienthandler-have-to-be-disposed – PaulF Sep 28 '15 at 09:29
  • @JonSkeet What is wroing If I call `HttpClient` `Dispose` in `Session` Finalizer ? – bot_insane Sep 28 '15 at 09:32
  • 1
    This question [already has an answer](http://stackoverflow.com/questions/16538494/types-that-own-disposable-fields-should-be-disposable-how-to-solve-this-warning) – Andy Brown Sep 28 '15 at 09:33
  • @AramKocharyan: Well what if (as is quite natural) you want the client to be disposed without having to wait for garbage collection? (Failure to dispose of `WebResponse` values is a well-documented way to hang an app, for example.) – Jon Skeet Sep 28 '15 at 09:37
  • @JonSkeet: Thanks, I understand. – bot_insane Sep 28 '15 at 10:26

1 Answers1

4

You should deal with this by implementing IDisposible on your class, the garbage collector will not automatically dispose of this object.

A simplified version is below, but check this article for the best practice and also this question & answer

public class Session : IDisposible
{
    private HttpClient m_httpClient;

    public Session()
    {
       m_httpClient = new HttpClient();
    }

    public void Dispose()
    {
       m_httpClient.Dispose();
    }
}
Community
  • 1
  • 1
Jamiec
  • 133,658
  • 13
  • 134
  • 193