c# cannot access a disposed object

20,385

If you don't care about the exception (i.e. it's not an "exception", it's the normal operating procedure and happens every time), you can just ignore/suppress it. (Just as long as it won't happen in a situation that indicates a real error)

If you want to suppress it more tidily, then you can set a flag that tells your callback that it should shut down, and have the callback actually do the closing/disposing of the socket. That way you can guarantee that there are no pending reads on the socket and won't get the exception (but this means it will hang about indefinitely, until another packet is received - which of course may never happen).

If you are in control of both ends of the communications link, then you can send an explicit "shutdown" message that tells the client that the connection should be closed (and this can of course be applied in the callback when the message is received).

(But I'd love to hear if anyone else has found a better solution as I have a similar situation with a UDP comms implementation)

Share:
20,385
iTEgg
Author by

iTEgg

:)

Updated on February 15, 2020

Comments

  • iTEgg
    iTEgg over 4 years

    I am making an server/client application.

    I set server socket to listening, and set BeginAccept() method. And when I closed server socket (Socket.Close()) to turn off server, an exception thrown from BeginAccept() method's async callback method. I inspected exception, and I found the exception saying me this:

    Message "Cannot access a disposed object named "System.Net.Sockets.Socket". Object name: "System.Net.Sockets.Socket"." String

    In my opinion, this is just this: "The socket disposed when I call Socket.Close() method, but the callback did not released before the socket closed."

    i did search on the net and found this is not an error but a designed exception as beginaccept was cancelled.

    my question how do i handle this excepton? what processing there needs to be for it?

    I'm just going to treat it as a normal event:

          OnNetworkEvents eventArgs = new OnNetworkEvents(false, "Ready", e.Message);
          OnUpdateNetworkStatusMessage(this, eventArgs);
    

    any comments are still welcome.

  • iTEgg
    iTEgg over 14 years
    (Just as long as it won't happen in a situation that indicates a real error)-> yes i cannot be sure of this. im also interested in knowing more about other's opinions. yes im writing both client and server in this case. im always for tidy code instead of code that just works.