Reputation: 781
I have a class where a socket is defined as a memberobject. Does i need to .Close() the socket, if i want to destroy the object of this class (set to null)
Upvotes: 1
Views: 736
Reputation: 3047
In short, yes.
Ideally, your class will implement IDisposable
which should close the socket. Not doing so means the socket object could persist in memory until the garbage collector gets it. If you plan to reconnect to the same endpoint you will have to, or else the underlying Windows libraries will throw an exception; (specifically Error 10056: A connect request was made on an already connected socket.)
Upvotes: 2
Reputation: 17003
Hi I think you come from C++ side in C# Close method call in behind the dispose method. After Close you do not have to do anything. The object will be disposed and later from GC will be set to null.
but if you have a socket in your class as member you have to apply the Dispose pattern!
And just dispose your socket in the dispose method of you created class see above the link.
public class DisposableResourceHolder : IDisposable {
private Socket socket; // handle to a resource
public DisposableResourceHolder(){
this.socket= ... // allocates the resource
}
public void Dispose(){
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing){
if (disposing){
if (socket!= null) socket.Dispose(); // HERE DISPOSE
}
}
}
Mark this as answer if this will solve your Problem!
Thanks
Upvotes: 1