C#命名管道,如何检测客户端断开连接

标签 c# .net named-pipes

我当前的命名管道实现是这样的:

while (true)
{
  byte[] data = new byte[256];                        
  int amount = pipe.Read(data, 0, data.Length);
  if (amount <= 0)
  {
      // i was expecting it to go here when a client disconnects but it doesnt
     break;
  }
  // do relevant stuff with the data
}

如何正确检测客户端何时断开连接?

最佳答案

设置读取超时并在发生超时时轮询 NamedPipeClientStream.IsConnected 标志。

读取超时将导致在超时持续时间内处于空闲状态的读取抛出 InvalidOperationException

如果您不阅读,并且想要检测断开连接,请在管道连接的生命周期内在工作线程上调用此方法。

while(pipe.IsConnected && !isPipeStopped) //use a flag so that you can manually stop this thread
{
    System.Threading.Thread.Current.Sleep(500);
}

if(!pipe.IsConnected)
{
    //pipe disconnected
    NotifyOfDisconnect();
}

关于C#命名管道,如何检测客户端断开连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18759125/

相关文章:

c# - DBML : s letter added to my table names

c# - 运行多个任务重用同一个对象实例

c# - NHibernate 在 WHERE IN 中使用 QueryOver

.net - XPath 注入(inject)缓解

c# - 在 native 命名管道和 System.IO 命名管道之间发送多条消息

c++ - 是否可以使用重定向到标准输入通过命名管道读取间歇性发送的数据?

c# - 除非删除 bin/obj 文件夹,否则 Xamarin.ios 不会生成

c# - 我怎样才能获得对属性 setter 的引用?

c# - out 用于多个输出值或返回组合值类型更好吗?

c++ - 如果服务器崩溃,命名管道会发生什么情况?