I have a class having a TcpClient member. e.g.:
class CustomNetClient
{
TcpClient tcp;
NetworkStream ns;
//...
}
I want to make sure that it is closed properly. So implemented IDisposable:
class CustomNetClient
{
TcpClient tcp;
NetworkStream ns;
public CustomNetClient()
{
tcp = new TcpClient("1.1.1.1",80);
ns = tcp.GetNetworkStream();
}
public void Dispose()
{
tcp.Close();
ns.Close();
}
//...
}
And in the application I call the CustomNetClient with using.
//...
using(CustomNetClient nc=new CustomNetClient)
{
// This will be a long long process, connection will stay open
}
Is this a good and enough practice or do you have any suggestions/concerns?
If you can release the tcpClient object ealier you should do that. That is if the life time of the CustemNetClient differs from when you no longer need the tcpClient you should release the tcpClient ealier. If however the CustomNetClient will cease to exist at the same time that you no longer need the tcpClient then your code would do just fine
The main question you need to ask yourself in general when wondering if you should release the resources of a member in the dispose method or not is
"Can I release them correctly any earlier"if the answer is yes then you should go for the early release if it’s no, then the dispose method is an appropriate choice