I was wondering if anyone knew the best way to dispose of a class that uses a Socket object and NetworkStream object? The class in question has an instance of NetworkStream and an instance of Socket that's used to create the NetworkStream.
this.socket = new Socket(
AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp)
{
ReceiveBufferSize = 65536,
SendBufferSize = 150
};
this.socket.Connect(
new IPEndPoint(
IPAddress.Parse(
Properties.Settings.Default.MpsServer2),
Properties.Settings.Default.MpsPort2));
this.stream = new NetworkStream(
this.socket, true);
In my Dispose method, should I do this?
this.stream.Close();
this.socket.Shutdown(SocketShutdown.Both);
this.socket.Close();
Is all of this necessary or is it overkill?
Socket
does not dispose of the associated NetworkStream
. I fired up reflector too be certain. (a tool to analyze .NET dlls and thet .NET libraries. Great tool. You have to end of the month to download the free version before it goes fully. commercial).
However, according to both the MDSN documentation and reflector the stream will close the socket but only if it has ownership of the socket. You can set that as the second parameter in the overloaded constructor.
You have to call Shutdown
in any case because if flushes the data. If you don't, you could lose data.