我有一個擁有TcpClient成員的類。例如:正確處置成員TcpClient
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
}
這是一個很好的和足夠的做法,或者你有任何建議/關注?