What happens if you never call Socket.EndConnect?
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?
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.
精彩评论