【发布时间】:2013-03-26 20:01:18
【问题描述】:
我正在创建一个 Windows 服务,该服务具有一个组件,该组件侦听命名管道以与从用户空间运行的程序进行交互。我使用来自this answer 的代码作为多线程服务器实现的基础,但是我从在紧密循环中调用的 ProcessNextClient 操作中获得了强烈的代码气味,如下所示。真的没有比重复捕获 IOException 并重试更好的方法来知道何时将另一个流的开口添加到命名管道吗?
public void ProcessNextClient()
{
try
{
NamedPipeServerStream pipeStream = new NamedPipeServerStream(PipeName, PipeDirection.InOut, 254);
pipeStream.WaitForConnection();
//Spawn a new thread for each request and continue waiting
Thread t = new Thread(ProcessClientThread);
t.Start(pipeStream);
}
catch (Exception e)
{//If there are no more avail connections (254 is in use already) then just keep looping until one is avail
}
}
【问题讨论】:
-
我想,我正在寻找的是:一种跟踪仍然处于活动状态并因此具有开放管道的线程/任务数量的方法;或者在不创建自旋锁的情况下阻止新的 NamedPipeServerStream 直到资源可用的方法。
标签: multithreading service while-loop namedpipeserverstream