【问题标题】:NamedPipeServerStream and WaitForConnection methodNamedPipeServerStream 和 WaitForConnection 方法
【发布时间】:2011-10-20 18:37:49
【问题描述】:

在使用NamedPipeServerStream 类时让我烦恼的是,对于每个传入连接,我需要创建新对象并调用它的方法WaitForConnection

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

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

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

流已断开连接。

有什么建议吗?

【问题讨论】:

    标签: c# named-pipes


    【解决方案1】:

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

    如果您真的想在单个线程上一次处理一个连接,请将您的循环翻过来:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-21
      • 2022-10-04
      相关资源
      最近更新 更多