I have a thread that uses TcpClient‘s BeginAcceptTcpClient() method. It resembles:
// this gets set elsewhere
ManualResetEvent _doneListening = new ManualResetEvent(false);
.. and in the thread procedure
while (true)
{
var result = BeginAcceptTcpClient(null, null);
var index = WaitHandle.WaitAny(new [] { _doneListening, result.AsyncWaitHandle });
if (0 == index)
{
break;
}
// do something with EndAcceptTcpClient(result)
}
Now, according to MSDN’s documentation:
The asynchronous BeginAcceptTcpClient operation must be completed by
calling the EndAcceptTcpClient method.
My question relates to the Cancel/Stop case of my thread — that is, after _doneListening.Set()— I really don’t want any more TcpClients. At the same time, I don’t want to leak memory.
Is it necessary to call EndAcceptTcpClient()? This will block, and I certainly don’t want it to (I want a fast thread exit). But will it leak memory otherwise? MSDN hints that Begin MUST be paired with an End. Is there a different pattern I should follow for effectively cancelling a potentially in-progress async operation?
EndAcceptTcpClientwon’t block if you’ve closed/disposed the TcpClient. So when you are done listening then close it. It will throw an exception in response to EndAcceptTcpClient, but that is OK. You can safely ignore/discard the exception.