客户端有时会这样做:
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();
}
}
}
答案 0 :(得分:0)
如果您阅读了所有数据,这似乎就会发生。
如果你做了一个" 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();