ThunderMusic said:
Ok... thanks, it helped me find a way... I was just stuck trying to find a
"normal" way like "close and don't do like if you are receiving a connection
attempt", but I will now just call Close and set a "flag" saying I'm
currently closing, so I won't call m_mySocket.EndAccept that would fail
anyway...
You will want to verify that this is a reasonable way to write the code,
if that's the way you really want to do it.
In particular, while I don't know the specifics off the top of my head,
I suspect it's not a good idea to leave an unmatched BeginAccept
hanging. At the very least, it could leave a dangling reference
somewhere, preventing your Socket instance from being garbage-collected,
and for all I know there might actually be some unmanaged resource left
allocated that causes more issues that your run-of-the-mill memory leak.
One indication that my suspicion is correct is that you are not required
to keep a reference to the Socket instance for the async methods to
work. That is, you could do something like the following:
void Init()
{
Socket socket = new Socket();
socket.Bind(...);
socket.Listen(...);
socket.BeginAccept(AcceptCallback, socket);
}
void AcceptCallback(IAsyncResult ar)
{
Socket socket = (Socket)ar.AsyncState, socketAccepted;
socketAccepted = socket.EndAccept(ar);
// etc.
}
Note in the above that there is no explicit retention of the reference
to the Socket instance. So something else is keeping that reference for
you. If you don't call EndAccept(), that something else has no way to
know that you don't need the reference any more, and so it will keep
hanging on to it.
I really think that you are making way too much of the question of the
exception. The exception _is_ a "normal" thing, even though it is
exceptional (that is, doesn't happen in every case). I think you will
be much happier in the long run writing the code in the way that
Microsoft intends. That is, just include a "catch
(ObjectDisposedException)" clause in your callback method and handle it
appropriately.
It's not like you're doing anything truly different from that anyway,
with respect to the flag (you have to handle the case one way or the
other, regardless of how you detect it), and now you have this extra
flag lying around that you have to maintain. I'd be much more concerned
about adding cruft like that to my architecture than of handling an
exception.
Pete