为了这个问题,我做了一个超级简化的例子:
using System;
using System.Net;
using System.Net.Sockets;
namespace Loop
{
class Program
{
public static void Main (string[] args)
{
TcpListener server = new TcpListener(IPAddress.Any, 1337);
server.Start();
Console.WriteLine("Starting listener on {0}:{1}", IPAddress.Any, 1337);
while (true)
{
if (server.Pending())
{
Console.WriteLine("Activity...");
Socket client = server.AcceptSocket();
IPEndPoint clientAddress = (IPEndPoint) client.RemoteEndPoint;
Console.WriteLine("Accepted client: {0}:{1}", clientAddress.Address, clientAddress.Port);
client.Close();
Console.WriteLine("Closed connection to: {0}:{1}", clientAddress.Address, clientAddress.Port);
}
else
{
// Currently takes 100% of my CPU (well, actually Core - 25%, but you get the idea).
// How do I idle (CPU @ 0%) the loop until pending connection?
}
}
}
}
}
评论已经包含了这个问题,但是是的,我如何让循环闲置直到有一个实际的挂起连接,这样我的 CPU 才不会融化?
当给定套接字上有挂起的连接时,有没有办法只在操作系统事件上监听和唤醒?(像libuv (node.js)这样的东西,这就是我添加单线程的原因)
我的实际实现是针对一个相当基本的 Reactor 事件循环,但是是的,我不知道如何用 C# 监听 OS 事件(如果有任何可能性)。
我知道BeginAccept
还有其他一堆 Async 家族,但由于他们的多线程性质,这些人是不可接受的。
另外,我知道我可以简单地Thread.Sleep
在循环中,但我正在寻找基于事件的行为。
PS 我正在使用 Mono,目标是 Linux 可执行文件。