NamedPipeServerStream和WaitForConnection方法

mar*_*rek 2 c# named-pipes

使用类时遇到的问题NamedPipeServerStream是,对于每个传入的连接,我需要创建新对象并调用它的方法WaitForConnection.

我想要做的是创建一个NamedPipeServerStream对象,然后在while循环中重复调用上述方法,如下所示:

NamedPipeServerStream s2;
using (s2 = new NamedPipeServerStream("pipe_name", PipeDirection.InOut)) {
    while(true) {
        ss2.WaitForConnection();
        //do something here
    }
}
Run Code Online (Sandbox Code Playgroud)

但是当我这样做时,我得到了消息

流已断开连接.

有什么建议?

Chr*_*son 5

如果你想使用NamedPipeServerStream,你需要使用它给你的编程模型,就像它将底层Windows句柄包装到命名管道内核对象一样.您不能像尝试那样使用它,因为这不是命名管道处理的工作方式.

如果你真的想在一个线程上一次一个地处理连接,那就把你的循环翻出来:

while (true)
{
  using (NamedPipeServerStream ss2 = new NamedPipeServerStream("pipe_name", PipeDirection.InOut)
  {
    ss2.WaitForConnection();
    // Stuff here
  }
}  
Run Code Online (Sandbox Code Playgroud)

更有可能的是,您需要一个并行处理连接的多线程管道服务器.如果是这样,有多种方式 - 搜索其他SO问题将会出现几种模式,例如此处此处.