C#命名管道流readline挂起

时间:2018-02-26 14:38:02

标签: c# stream streamreader named-pipes hang

我很困惑。我有命名管道的客户端/服务器结构,问题是在一些随机点,经过一段时间的工作后它只挂在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();
        }
    }
 }

1 个答案:

答案 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();