我正在创建一个 Windows 服务,该服务具有一个组件,该组件侦听命名管道以与从用户空间运行的程序进行交互。我已将此答案中的代码用作多线程服务器实现的基础,但是我从在紧密循环中调用的 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
}
}