【发布时间】:2019-11-01 16:23:28
【问题描述】:
我使用的数据通过 UDP 到达。我想在不阻塞主线程的情况下创建几个 UDP 连接。我已经同步和异步地实现了 UDP 连接,但是它们都保持主线程锁定。我的代码永远不会到达 'Console.WriteLine("Past the Async")'
目标是让 UDP 连接在后台运行。
谁能提供一些关于下一步要尝试什么,或者如何正确实现允许主线程仍然接收命令的异步版本的 UDP 的指导?
我将异步版本的 ReceiveUdpData() 注释掉。
class Program
{
// The whole point of this is to not block the main thread.
static async Task Main(string[] args)
{
ReceiveUdpData();
Console.WriteLine("Past Receive UDP Data");
await foreach (var item in MessagesAsync())
{
Console.WriteLine(item);
}
Console.WriteLine("Past The Async");
}
// Synchronous connection to UDP.
public static void ReceiveUdpData()
{
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
var count = 0;
using (UdpClient client = new UdpClient(12345))
{
while (true)
{
Byte[] receiveBytes = client.Receive(ref remoteEndPoint);
count++;
Console.WriteLine(count);
}
}
}
// Async UDP connection
private static async IAsyncEnumerable<object> MessagesAsync()
{
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
var count = 0;
using (UdpClient client = new UdpClient(12345))
{
while (true)
{
UdpReceiveResult test = await client.ReceiveAsync();
count++;
yield return test.ToString();
}
}
}
}
【问题讨论】:
标签: c# multithreading asynchronous udp