【发布时间】:2011-04-06 03:12:29
【问题描述】:
我有一个 C# 程序,其中有很多(比如说大约一千个)打开的 TcpClient 对象。我想进入一种状态,等待任何这些连接发生某些事情。
我宁愿不为每个连接启动一个线程。
有点像……
while (keepRunning)
{
// Wait for any one connection to receive something.
TcpClient active = WaitAnyTcpClient(collectionOfOpenTcpClients);
// One selected connection has incomming traffic. Deal with it.
// (If other connections have traffic during this function, the OS
// will have to buffer the data until the loop goes round again.)
DealWithConnection(active);
}
附加信息:
TcpClient 对象来自 TcpListener。
目标环境将是 MS .NET 或 Mono-on-Linux。
当连接打开时,该协议要求长时间处于空闲状态。
【问题讨论】:
-
在 Unix 世界中,您将使用
select系统调用来执行此操作。我敢肯定 Windows 中有一些类似的东西。 -
您对“每个连接都有一个线程”的假设是有缺陷的。线程池与 APM 方法相结合是解决此类问题的方法。只需几个线程就可以为许多客户提供服务。我给出的这个答案应该证明信息丰富:stackoverflow.com/questions/3153959/…
-
@spender - 你建议我 BeginRead all ~1000 TcpClients 并处理回调中的任何流量?如果您想将其写成答案,我会接受。
标签: c# .net tcpclient single-threaded