C#在UdpClient接收上使用异步/等待 [英] C# Use async/await on UdpClient Receive

查看:335
本文介绍了C#在UdpClient接收上使用异步/等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码使用Task异步接收并在控制台中显示接收到的结果:

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));
             }
         }
    });
}

我想学习如何使用async/await函数,所以我想了解如何通过使用async/await异步创建函数ReceiveMessage()?

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:

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

您不再需要使用线程的 Task.Run().不需要该线程.现在,该方法在 await ReceiveAsync()时返回到调用方.
ReceiveAsync()完成时,该方法(最终)将在 Console.WriteLine()中恢复.

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().

这篇关于C#在UdpClient接收上使用异步/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆