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?
If you want the whole method to be awaitable, simply change it to that:
You don't need
Task.Run()
anymore, which would use a thread. That thread is not needed. The method now returns to the caller whileawait
ingReceiveAsync()
.When
ReceiveAsync()
finishes, the method is (eventually) resumed atConsole.WriteLine()
.