NamedPipeServerStream和WaitForConnection方法

时间:2011-10-20 18:37:49

标签: c# named-pipes

使用类NamedPipeServerStream时出现的问题是我需要创建新对象并调用方法WaitForConnection

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

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

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

  

Stream已断开连接。

有什么建议吗?

1 个答案:

答案 0 :(得分:5)

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

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

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

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

相关问题