Reputation: 186
I use sockets, and when I try to close the socket, I get an
ObjectDisposedException: Cannot access a disposed object Object name: 'System.Net.Sockets.Socket'.
exception.
socket.Close();
socket.Shutdown(SocketShutdown.Both); <- exception
Why is this happening? why does the garbage collector clean it out?
Upvotes: 2
Views: 4715
Reputation: 23228
Remarks section of Socket.Close
documentation tells you
For connection-oriented protocols, it is recommended that you call
Shutdown
before calling theClose
method. This ensures that all data is sent and received on the connected socket before it is closed.
So, you should call Shutdown
before Close
, not the after
socket.Shutdown(SocketShutdown.Both);
socket.Close();
Upvotes: 4
Reputation: 1062770
Close
is effectively synonymous with Dispose
in many cases. In the case of a socket, you should use Shutdown
before Close
/Dispose
(or not at all).
Upvotes: 3