0

I have two UDP clients:

UdpClient _udpReceiver

and

UdpClient _udpSender

For receiving a message I'm using _udpReceiver.BeginReceive(...);

And for sending: _udpSender.BeginSend(data, data.Length, new AsyncCallback(StopCallback, _udpSender);

What I'm trying to achieve is to stop any sending and receiving and somehow unbind the ports which _udpReceiver and _udpSender are using. But with no success:

  private void StopCallback(IAsyncResult ar)
    {
       try
        {
            UdpClient client = (UdpClient)ar.AsyncState;
            client.EndSend(ar);     
            client.Close(); //app crashes here   
            _udpSender.Client.Close(); //and here              
            _udpReceiver.Client.Close(); //and here too
        }
        catch (ObjectDisposedException ex)
        {
            //and this one is never getting caught
        }
    }

UPD: attached link to a project which reproduces the crash

http://1drv.ms/1kWWJKA

lena
  • 1,181
  • 12
  • 36
  • Can't reproduce the first crash. The second is normal: you can't close `_udpSender.Client` *again*, you've just closed it. The fact that you don't enter the `catch` is also normal, the crashes are `NullReferenceException`. Have you tried using a debugger? – user703016 Apr 14 '14 at 09:20
  • What do you mean by "using a debugger"? I set a breakpoint into the catch block and it was never hit. Neither `Exception` nor `NullReferenceException` were hit as well. – lena Apr 14 '14 at 09:34
  • In Output window of VS I can see that It was an ObjectDisposedException but I'm unable to catch it before the app crashes. I even tried to set global catch on the whole app, it did not helped. – lena Apr 14 '14 at 09:36
  • I'm unable to reproduce your scenario. Please post the minimal example, short but complete, which reproduces it. – user703016 Apr 14 '14 at 09:47
  • http://1drv.ms/1kWWJKA Please press 'Start listen' and then 'Send message and stop' and it will crash. – lena Apr 14 '14 at 10:17
  • http://stackoverflow.com/questions/4662553/how-to-abort-sockets-beginreceive I believe that closing a socket is what I need but still I'm unable to catch these exceptions and my app just crashes... – lena Apr 15 '14 at 06:31
  • Try to read here: http://stackoverflow.com/questions/41019997/udpclient-receiveasync-correct-early-termination/41041601#comment69291144_41041601 – EgoPingvina Dec 08 '16 at 14:46

0 Answers0