cla*_*amp 5 .net c# 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
}
Run Code Online (Sandbox Code Playgroud)
如何正确检测客户端何时断开连接?
设置读取超时并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();
}
Run Code Online (Sandbox Code Playgroud)