Marcel
Marcel

Reputation: 15732

Where to close a TcpClient member

Context: I have a class that implements a "Session", maintaining a TCP connection to a server during it's lifetime. In the constructor, I create a TcpClient instance with a given IP address and port of a server to connect to.

   public Session(IPAddress ipAddress)
   {
       Client = new TcpClient(ipAddress.ToString(), 1234); //create a client to a server which we will later use to work with
       DataStream = Client.GetStream(); //get the stream for later usage
   }

Objects of this session will occasionally send and receive data to and from their associated server.

My question now is: Where should I close the TcpClient and its underlying NetworkStream?

Should I implement IDisposable? But What happens if the user of my class forgets to call Dispose?

Should I implement a Destructor (aka Finalizer)? But AFAIK I should never access managed resources from there?

Thanks for helping me out!

Upvotes: 0

Views: 734

Answers (3)

supercat
supercat

Reputation: 81179

Very few classes should have cleanup finalizers. If the code which is responsible for managing an IDisposable instance neglects to call IDisposable.Dispose before abandoning it, the code should be fixed. Adding a finalizer might mask the problem, but won't solve it, and will very likely introduce Heisenbugs™. Further, if a class is responsible for things which implement IDisposable and have finalizers, the class will need to ensure that those things' Dispose method gets called (likely from its own Dispose method), but will not be responsible for calling those things' finalizers from its own. Indeed, when a class' finalizer is running, one of the following three things will usually be true about any finalizable objects to which it holds a reference:

  1. It will already have been finalized.
  2. It will already be in a queue to be finalized soon after the present finalizer is done.
  3. A live reference to it will exist somewhere else, and it shouldn't be cleaned up yet.

In any of those cases, the proper thing for the finalizer to do with the object is "nothing".

Upvotes: 0

user111013
user111013

Reputation:

See the myriad topics on "When should I Implment IDisposable?"

The trigger for you, being that you have a field (Client) which implements IDisposable. Thus, your class should be Disposable.

Upvotes: 1

jgauffin
jgauffin

Reputation: 101150

Should I implement IDisposable?

Yes

But What happens if the user of my class forgets to call Dispose?

you should follow the Disposable pattern as defined here: http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx

Upvotes: 2

Related Questions