I am receiving data from UdpClient via the usual async callback:
private void OnUdpData(IAsyncResult result)
{
byte[] data = _udpReceive.EndReceive(result, ref _receiveEndPoint);
//Snip doing stuff with data
_udpReceive.BeginReceive(OnUdpData, null);
}
When I Close()
the UdpClient in the main thread, the callback fires as I would expect, but at this point _udpReceive
is already disposed and I get an ObjectDisposedException
when I try and call EndReceive()
. I was expecting to just get an empty buffer.
What is the correct way to handle this? Is there some member of UdpClient
I can check before trying to use it, or it the only way to wrap it all in a try{}
and catch the ObjectDisposedException
? That seems pretty nasty for a normal close.
EndReceive
? My impression was that except for some types ofIAsyncResult
which do not tie up resources (e.g. the return value ofControl.BeginInvoke
) one is supposed to always callEndXX
after everyBeginXX
. Note that the exception one catches is not a sign that theEndReceive
operation failed, but is rather the consequence of "successful"EndReceive
call relaying the exception which resulted in the receive attempt. – Thorton