我当前的命名管道实现是这样的:
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/