远程关闭后保持管道打开的最佳方法
使用本教程我想出了下面的代码。我的客户端经常运行。它通过点击激活,并且在某些情况下可以同时启动两次。我担心一个客户端可能会关闭,而另一个客户端会打开,这会导致管道在短短的几毫秒内关闭。保持管道畅通的最佳方法是什么?
static public void ThreadStartServer()
{
while (true)
{
using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("mytestpipe"))
{
Console.WriteLine("[Server] Pipe created {0}", pipeStream.GetHashCode());
pipeStream.WaitForConnection();
Console.WriteLine("[Server] Pipe connection established");
using (StreamReader sr = new StreamReader(pipeStream))
{
string temp;
while ((temp = sr.ReadLine()) != null)
{
Console.WriteLine("{0}: {1}", DateTime.Now, temp);
}
}
}
}
Using this tutorial i came up with the code below. My client is ran frequently. Its activated via clicks and possibly can be launched twice at the same moment in certain circumstance. I am worried one client may close while another client opens which causes the pipe to be closed in that slim few milliseconds. Whats the best way to keep the pipe open?
static public void ThreadStartServer()
{
while (true)
{
using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("mytestpipe"))
{
Console.WriteLine("[Server] Pipe created {0}", pipeStream.GetHashCode());
pipeStream.WaitForConnection();
Console.WriteLine("[Server] Pipe connection established");
using (StreamReader sr = new StreamReader(pipeStream))
{
string temp;
while ((temp = sr.ReadLine()) != null)
{
Console.WriteLine("{0}: {1}", DateTime.Now, temp);
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使您的管道服务器成为多线程,其中一个线程专用于监听。请参阅这些 答案:
Make your pipe server multi-threaded, with one thread dedicated to listening. See these answers: