代码之家  ›  专栏  ›  技术社区  ›  Greg Buehler

命名管道暂停线程?

  •  0
  • Greg Buehler  · 技术社区  · 15 年前

    我正试图通过一个命名管道将更新推送到一个进程中,但这样做的话,我的进程循环现在可能会停止 while ((line = sr.ReadLine()) != null) . 由于这是我第一次涉足命名管道,我对可能的错误有点迷惑。

    void RefreshThread()
    {
        using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("processPipe", PipeDirection.In))
        {
            pipeStream.WaitForConnection();
    
            using (StreamReader sr = new StreamReader(pipeStream))
            {
                for (; ; )
                {
                    if (StopThread == true)
                    {
                        StopThread = false;
                        return;                 // exit loop and terminate the thread
                    }
    
                    // push update for heartbeat
                    int HeartbeatHandle = ItemDictionary["Info.Heartbeat"];
                    int HeartbeatValue = (int)Config.Items[HeartbeatHandle].Value;
                    Config.Items[HeartbeatHandle].Value = ++HeartbeatValue;
                    SetItemValue(HeartbeatHandle, HeartbeatValue, (short)0xC0, DateTime.Now);
    
                    string line = null;
                    while ((line = sr.ReadLine()) != null)
                    {
                        // line is in the format: item, value, timestamp
                        string[] parts = line.Split(',');
    
                        // push update and store value in item cache
                        int handle = ItemDictionary[parts[0]];
                        object value = parts[1];
                        Config.Items[handle].Value = int.Parse(value);
                        DateTime timestamp = DateTime.FromBinary(long.Parse(parts[2]));
                        SetItemValue(handle, value, (short)0xC0, timestamp);
                    }
    
                    Thread.Sleep(500);
                }
            }
        }
    }
    

    Queue<string> 对于数据,使用一个单独的线程来处理管道,并将通过管道接收的字符串推入

    2 回复  |  直到 15 年前
        1
  •  1
  •   Hans Passant    15 年前

    根据设计,PipeStream.Read()是一个阻塞调用。您可以改用BeginRead()。当然,这使得文本的数据格式不如恒星格式。不是真正的问题,请使用PipeTransmissionMode.Message。

        2
  •  0
  •   Stephen Cleary    15 年前

    客户端是否处理其命名的管道连接?如果客户端从未关闭,服务器将永远等待。