Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Use async/await on UdpClient Receive

The following code uses Task to receive asyncronously and shows the received result in the console:

private void ReceiveMessage()
{
    Task.Run(async() => 
    {
         using(var udpClient = new UdpClient(15000))
         {
             while(true)
             {
                 var receivedResult = await udpClient.ReceiveAsync();
                 Console.Write(Encoding.ASCII.GetString(receivedResult.Buffer));
             }
         }
    });
}

I want to learn how to use async/await functions so I would like to know how to make the function ReceiveMessage() asynchronously by using async/await?

like image 525
FinFon Avatar asked Oct 21 '25 03:10

FinFon


2 Answers

If you want the whole method to be awaitable, simply change it to that:

private async Task ReceiveMessage()
{
     using(var udpClient = new UdpClient(15000))
     {
         while(true)
         {
             var receivedResult = await udpClient.ReceiveAsync();
             Console.Write(Encoding.ASCII.GetString(receivedResult.Buffer));
         }
     }
}

You don't need Task.Run() anymore, which would use a thread. That thread is not needed. The method now returns to the caller while awaiting ReceiveAsync().
When ReceiveAsync() finishes, the method is (eventually) resumed at Console.WriteLine().

like image 114
René Vogt Avatar answered Oct 23 '25 17:10

René Vogt


The code you have is valid if you want it to be fire and forget, listening on a separate thread. If you not want this, I would remove the Task.Run and be sure to return a Task in your method, like this:

private async Task ReceiveMessage()
{
    using (var udpClient = new UdpClient(15000))
    {
        while (true)
        {
            var receivedResult = await udpClient.ReceiveAsync();
            Console.Write(Encoding.ASCII.GetString(receivedResult.Buffer));
        }
    }
}
like image 34
Stuart Avatar answered Oct 23 '25 16:10

Stuart