0

I'm currently trying to refactor some old code and reached a point where I'm trying to get UDP communication asynchronous. My old code receives packets:

ClientListener = new UdpClient(ClientListenPort);
ServerEp = new IPEndPoint(IPAddress.Any, ClientListenPort);
try
{
    while (!stop)
    {
         byte[] ReceivedData = ClientListener.Receive(ref ServerEp);
         LastReceivedTimeMS = Environment.TickCount;
         if (!FoundServer)
         {
             ServerIP = ServerEp.Address.ToString();
             FoundServer = true;
         }
         HandleReceiveData(ReceivedData);
     }
}
 catch (Exception e)
{
    Debug.Log("Error: " + e);
}

whereas the asynchronous way does not receive anything (hangs). Does someone have an idea what I'm doing wrong?

ClientListener = new UdpClient(ClientListenPort);
ServerEp = new IPEndPoint(IPAddress.Any, ClientListenPort);
try
{
    Task.Run(async () =>
    {
        while (!stop)
        {
            UdpReceiveResult receivedResults = await ClientListener.ReceiveAsync();
            if (!FoundServer)
            {
                ServerIP = receivedResults.RemoteEndPoint.Address.ToString();
                ServerEp = receivedResults.RemoteEndPoint;
                FoundServer = true;
            }
            HandleReceiveData(receivedResults.Buffer);
        }
    });
}
catch (Exception e)
{
    Debug.Log("Error: " + e);
}
Ian Kemp
  • 28,293
  • 19
  • 112
  • 138
Hagi
  • 140
  • 1
  • 8
  • When you say 'does not receive anything' do you mean that the program quits right away? – mikelegg Mar 12 '21 at 11:10
  • At UdpReceiveResult receivedResults = await ClientListener.ReceiveAsync(); it awaits endless, so there is no error and it doesnt quit – Hagi Mar 12 '21 at 11:20
  • Does this answer your question? [C# Use async/await on UdpClient Receive](https://stackoverflow.com/questions/41428589/c-sharp-use-async-await-on-udpclient-receive) – Ian Kemp Mar 12 '21 at 12:08
  • 2
    The try/catch is not doing anything since it only checks if Task.Run throws, you should put the try/catch inside the delegate. – JonasH Mar 12 '21 at 12:33
  • @JonasH that's answer, there was an error in HandleRecieveData... Thanks – Hagi Mar 12 '21 at 14:37

0 Answers0