以下代码使用Task来异步接收并在控制台中显示收到的结果:
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()?
答案 0 :(得分:4)
如果您希望整个方法可以等待,只需将其更改为:
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()
恢复。
答案 1 :(得分:1)
只需在函数中添加另一个async / await:
private async void receiveMessage()
{
await Task.Run(async() =>
{
using(var udpClient = new UdpClient(15000))
{
while(true)
{
var receivedResult = await udpClient.ReceiveAsync();
Console.Write(Encoding.ASCII.GetString(receivedResult.Buffer));
}
}
});
}
如果您想编写一个可以等待的方法,请返回一个任务:
private Task foo(){
Task doStuff = new Task(() => {});
doStuff.Start();
return doStuff;
};
//Another method
private async void bar()
{
await foo();
}
<强>更新强> 如下所述,您确实不需要在线程池内的线程上执行该任务。这没错,但没用。为了更好地使用,您可以使用:
private async void receiveMessage()
{
using(var udpClient = new UdpClient(15000))
{
while(true)
{
var receivedResult = await udpClient.ReceiveAsync();
Console.Write(Encoding.ASCII.GetString(receivedResult.Buffer));
}
}
}
答案 2 :(得分:0)
如果你想让它成为火,忘记在一个单独的线程上,你拥有的代码是有效的。如果您不想这样做,我会移除Task.Run
,并确保在您的方法中返回Task
,如下所示:
private async Task ReceiveMessage()
{
using (var udpClient = new UdpClient(15000))
{
while (true)
{
var receivedResult = await udpClient.ReceiveAsync();
Console.Write(Encoding.ASCII.GetString(receivedResult.Buffer));
}
}
}