我很困惑。我有命名管道的客户端/服务器结构,问题出在某个随机点,经过一段时间的工作后,它只是挂在streamReader.ReadLine();上
它只是停下来,不再继续。我很困惑,我根本不知道发生了什么,也不知道如何调试它,为什么以及何时发生。有任何想法吗?
客户端有时会这样做:
private void Connect()
{
stream = new NamedPipeClientStream(".", "MP9", PipeDirection.InOut);
try
{
stream.Connect(120);
}
catch (Exception e)
{
run = false;
return;
}
//Initialising Readers/Writers
sr = new StreamReader(stream);
sw = new StreamWriter(stream);
}
private string SendMessage(string msg)
{
Debug.WriteLine("Will listen for message " + msg);
string msgFrom = "";
if (run)
{
string toReturn = "";
lock (locker)
{
sw.WriteLine(msg); //Writing command to the pipes
stream.WaitForPipeDrain(); //Waiting for another process to read the command
msgFrom = sr.ReadLine(); //Reading
}
}
return msgFrom;
}
我的服务器有一个线程,它监听任何消息,并在需要时做出响应。运行 X 小时后,它将停止在 ReadLine 处,没有错误等。只是停在线路上,不再继续前进。但是应用程序仍在运行,它没有挂起,只是这个侦听器线程似乎挂起......
void Listen()
{
try
{
stream.WaitForConnection();
sw.AutoFlush = true;
string messageTo = "";
while (running) //Main loop of the thread
{
messageFrom = "";
//HERE IT CAN JUST HANG AND NOT GO FURTHER....
messageFrom = sr.ReadLine(); //Reading
//populate message to with data, if is needed to respond
sw.WriteLine(messageTo);
stream.WaitForPipeDrain();
}
}
}
如果您读取所有数据,似乎就会发生这种情况。
如果您在阅读之前执行“Peek()”并检查大于 0 的值,您应该能够解决此问题。
stream.WaitForConnection();
sw.AutoFlush = true;
string messageTo = "";
while (running) //Main loop of the thread
{
messageFrom = "";
if(sr.Peek() > 0)
{
messageFrom = sr.ReadLine(); //Reading
//populate message to with data, if is needed to respond
sw.WriteLine(messageTo);
}
stream.WaitForPipeDrain();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)