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) { } }, null); } catch (SocketException) { } } else {
Also use asynchronous shutdown to avoid blocking.
[1] The exception is Control.BeginInvoke in WinForms, where the exception is explicitly documented.
Richard
source share