System.IO.Exception:管道在客户端被破坏

时间:2014-10-21 03:34:09

标签: c# named-pipes inter-process-communicat broken-pipe

我有两个Windows应用程序,并使用命名管道发送和接收它们之间的数据列表。 使用BinaryFormatter类的序列化/反序列化机制。

服务器:

  static void StartServer()
    {
        var server = new NamedPipeServerStream("PipesEnroll", PipeDirection.InOut);

            while (true)
            {
                StreamReader reader = new StreamReader(server);
                StreamWriter writer = new StreamWriter(server);
                string terminalTemplate;
                string matcherTemplate;
                int mathVersionNumber = 9;
                int numberFingers;
                BinaryFormatter formatterDeserialize = new BinaryFormatter();
                List<byte[]> retrievedList = (List<byte[]>)formatterDeserialize.Deserialize(reader.BaseStream);
                bool isOk = Enroll.EnrollWithoutWCF(retrievedList, mathVersionNumber, out terminalTemplate, out matcherTemplate, out numberFingers);
                List<String> sendList = new List<string>();
                sendList.Add(isOk.ToString());
                sendList.Add(terminalTemplate);
                sendList.Add(matcherTemplate);
                sendList.Add(numberFingers.ToString());
                BinaryFormatter formatterSerialize = new BinaryFormatter();
                formatterSerialize.Serialize(writer.BaseStream, sendList);
                server.Disconnect();
       }

客户端:

                    using (var client = new NamedPipeClientStream(".", "PipesEnroll", PipeDirection.InOut))
                        {
                            client.Connect();
                            StreamReader reader = new StreamReader(client);
                            StreamWriter writer = new StreamWriter(client);

                                BinaryFormatter formatterSerialize = new BinaryFormatter();
                                formatterSerialize.Serialize(writer.BaseStream, images);
                                // writer.Write(stream);
                                // writer.Flush();
                                BinaryFormatter formatterDeserialize = new BinaryFormatter();
                                List<String> retrievedList = (List<String>)formatterDeserialize.Deserialize(reader.BaseStream);
                                bool isOK = Convert.ToBoolean(retrievedList[0]);
                                string terminalTemplate = retrievedList[1];
                                string matcherTemplate = retrievedList[2];
                                int numberFingers = Convert.ToInt32(retrievedList[3]);

}

但执行formatterSerialize.Serialize(writer.BaseStream,images)时,客户端出现异常“System.IO.Exception:Pipe is broken”;在调试模式下。

有人对如何避免此问题有任何建议吗?

1 个答案:

答案 0 :(得分:1)

StreamWriter属于NamedPipeClientStream。如果部署了NamedPipeClientStream,则其进程的一部分也在处理StreamWriter。如果由于任何原因StreamWriter在代码的任何其他部分中被关闭/处置,结果将是管道被破坏。

1)检查formatterSerialize.Serialize是否未关闭StreamWriter。

2)还要确保在退出使用NamedPipeClientStream之前刷新StreamWriter。