I feel, that I am misunderstanding something about async sockets in .Net. The situation is as follows : I have 1 async socket client and 1 async socket server. They communic
No, this is correct -- the callback you specify in a Begin...
operation will always be called, even if you close the socket (if you close the socket, it will be called because of that). You should be catching the ObjectDisposedException
you get on the EndAccept
and then return without further action. Closing/disposing a socket/listener is the only way to cancel an asynchronous operation on it. (EndAccept
can also produce SocketException
, which should be handled normally.)
Using a flag you maintain yourself to check if the listener is still available is asking for trouble, because you're introducing shared state that needs to be synchronized (volatile reads and the like). You can easily introduce race conditions that way. The listener already maintains such a flag for you internally, which it uses to throw ObjectDisposedException
, so I'd just use that. It's true that under normal circumstances catching ObjectDisposedException
is a possible sign of a coding error (since you're supposed to know when an object is disposed), but with asynchronous code it's pretty standard.