我有一个有TcpClient成员的类。 e.g:
class CustomNetClient
{
TcpClient tcp;
NetworkStream ns;
//...
}
我想确保它已正确关闭。所以实施了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();
}
//...
}
在应用程序中,我使用CustomNetClient
调用using
。
//...
using(CustomNetClient nc=new CustomNetClient)
{
// This will be a long long process, connection will stay open
}
这是一个好的和足够的做法,或者你有任何建议/关注?
答案 0 :(得分:0)
如果你可以释放tcpClient对象,你应该这样做。也就是说,如果CustemNetClient的生命周期与不再需要tcpClient的时间不同,则应释放tcpClient ealier。但是,如果CustomNetClient在您不再需要tcpClient的同时将不再存在,那么您的代码就可以了。
当您想知道是否应该在dispose方法中释放成员的资源时,您需要问自己的主要问题是"Can I release them correctly any earlier"
如果答案是肯定的那么你应该去提前发布不行,那么处置方法是一个合适的选择
答案 1 :(得分:0)
我建议实现终结器方法和IDisposable接口实现。如果由于某种原因,不使用using语句,GC将调用终结器并且终结器将释放资源。这基本上是一种故障安全机制。