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!
Yes
you should follow the Disposable pattern as defined here: http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx