I always get some form of exception inside of the receive callback stating that the socket is disposed. This is, of course, true. The problem is, why am I getting a message after I have closed down and shutdown the sockets? I'm not too familiar with every in and out of C# (don't think I'll ever get used to managed code. Can I have C back?) Included, I have the receive callback, which parses a message and continues to listen. I also included the CloseConnections method, which is called within the Form Closing event.
Does Shutdown and Close not stop the messages from being received? If so, how can I so that the GC may dispose of my sockets without receiving a message afterwards?
"An unhandled exception of type 'System.ObjectDisposedException' occurred in system.dll
Additional information: Cannot access a disposed object named "System.Net.Sockets.Socket"."
private static void ReceiveCallback(IAsyncResult ar){ // End Receive StateObject stateObject = (StateObject)ar.AsyncState; if(stateObject != null && stateObject.Socket != null && stateObject.DataBuffer != null && stateObject.EventMap != null) { int bytesReceived = stateObject.Socket.EndReceive(ar); if(bytesReceived > 0) { // Parse Data SocketConnection.ParseReceiveBuffer(stateObject); } } if(stateObject != null && stateObject.Socket != null && stateObject.DataBuffer != null && stateObject.EventMap != null) { // Begin Receive stateObject.Socket.BeginReceive(stateObject.DataBuffer, 0, stateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), stateObject); }}
public void CloseConnections(){ // Receive if(_recvSocket != null) { _recvSocket.Shutdown(SocketShutdown.Both); _recvSocket.Close(); _recvSocket = null; _recvState.Socket = null; _recvState = null; } // Send if(_sendSocket != null) { _sendSocket.Shutdown(SocketShutdown.Both); _sendSocket.Close(); _sendSocket = null; _sendState.Socket = null; _sendState = null; }}