Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if you never call Socket.EndConnect?

Tags:

.net

sockets

Using .Net 4.0. I have a some code which tries to open a connection using BeginConnect and a callback. If the user tries to stop the programming in the next few moments I try to disconnect. At that point I set a flag to indicate whether or not the EndConnect needs to be called from the callback. If the flag is set to false I skip the EndConnect because the socket has been trashed anyway.

At this point the user can try connect again immediately. I don't see this happening but just in case. Now a new socket is created and BeginConnect is called again.

Is it fine to never call the EndConnect method?

like image 669
uriDium Avatar asked Jan 17 '11 09:01

uriDium


Video Answer


1 Answers

In all cases (except one[1]) a call to BeginZZZ needs a matching EndZZZZ.

Otherwise non-managed resources are going to be leaked, and quite possibly the action ZZZZ will not correctly complete—potentially corrupting further uses of ZZZZ later.

Sockets are pretty robust against abuse (the IP stack has to handle network failures and packets out of order), but that doesn't make it good practice.

If you are using a flag to track "shutting down", better to call EndConnect and then close the socket immediately. After all the connect could itself fail, and a disconnect not needed (EndConnect throws SocketException). Something like:

mySocket.BeginConnect(address, port, ia => {
  if (shuttingDown) {
    try {
      mySocket.EndConnect(ia);
      mySocket.BeginDisconnect(false, iaa = {
        try {
          mySocket.EndDisconnect(iaa);
        } catch (Exception) { /* Ignore */ }
      }, null);
    } catch (SocketException) { /* Ignore */ }
  } else {
    // Normal connection handling
  }
}, null);

Also using async disconnect to avoid blocking there.


[1] The Exception is Control.BeginInvoke in WinForms, where the exception is explicitly documented.

like image 88
Richard Avatar answered Oct 31 '22 05:10

Richard