Reputation: 15732
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
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:
In any of those cases, the proper thing for the finalizer to do with the object is "nothing".
Upvotes: 0
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
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