What happens if you never call Socket.EndConnect?

Using .Net 4.0. I have code that tries to open a connection using BeginConnect and a callback. If the user tries to stop programming in the next few moments, I try to disconnect. At this point, I set a flag indicating whether to call EndConnect from the callback. If the flag is set to false, I skip EndConnect because the socket was corrupted anyway.

At this point, the user can try to reconnect again. I do not see this, but just in case. Now a new socket is created and BeginConnect is called again.

Can I never call the EndConnect method?

+6
sockets
source share
1 answer

In all cases (except for one [1] ), calling BeginZZZ requires an EndZZZZ .

Otherwise, uncontrolled resources will be skipped, and perhaps the ZZZZ action will not be completed correctly, it may hurt the further use of ZZZZ later.

Sockets are pretty abusive (the IP stack should handle network failures and packets out of order), but that doesn't make it a good practice.

If you use the flag to track "shutdown", it is better to call EndConnect , and then immediately close the socket. In the end, the connection itself may fail, and disconnection is not required ( 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 use asynchronous shutdown to avoid blocking.


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

+3
source share

All Articles