I know that i have to dispose all unmanaged resources in a class or form.. but what if i passed a socket to a class then i want to dispose the class and keep the socket!
so when i initialized the class .. i passed the socket i use in form1 to the class.. im wondering does the socket in form1.cs disposes if i called socket.dispose() from the class?
do i have to dispose the socket when i dispose the class or just socket = null will be fine? (but i need the socket alive even if i wanted to dispose the class, because i want to keep receiving commands from server).
the class:
public class TM
{
Socket client;
public TM(Socket socket)
{
client = socket;
}
public void Dispose()
{
client = null; // or client.Dispose()
GC.SuppressFinalize(this);
}
~TM()
{
Dispose();
}
}
form1.cs
TM tm = new TM(client);
private void whatever()
{
StreamReader sr = new StreamReader(new NetworkStream(client));
while ((cmd = sr.ReadLine()) != null) //this socket need to keep receiving commands even if i disposed the class
{
Console.WriteLine(cmd);
}
}
private void Button1_Click(object sender, EventArgs e)
{
tm.Dispose();
}
sorry for my bad english and i hope you understood my point.. thanks in advance.
First, if you’re going to use
Dispose, just implementIDisposable. MSDN shows the proper way of implementing the pattern you’re trying to do.To the actual question: Since you’re not actually disposing of the
Socketin theDisposeofTM, it gets neither closed or disposed. The way it’s shown implemented, it is up to the caller to manage the lifecycle ofsocket. IfTMis not responsible for socket creation, it should not be responsible for socket cleanup either. Doing so could lead to hard to trace down bugs and unexpected behavior.