C#在UdpClient接收上使用异步/等待 [英] C# Use async/await on UdpClient Receive
问题描述
以下代码使用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 await
ing ReceiveAsync()
.
When ReceiveAsync()
finishes, the method is (eventually) resumed at Console.WriteLine()
.
这篇关于C#在UdpClient接收上使用异步/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!