System.IO.Exception: Pipe is broken

后端 未结 3 804
夕颜
夕颜 2021-02-02 11:20

I have two .NET applications that talk to each other over a named pipe. Everything is great the first time through, but after the first message is sent, and the server is going

相关标签:
3条回答
  • 2021-02-02 11:53

    The problem for me has occurred when I would call pipe.WaitForConnection() from the server, after the client disconnected. The solution is to catch the IOException and call pipe.Disconnect(), and then call pipe.WaitForConnection() again:

    while (true)
    {
        try
        {
            _pipeServer.WaitForConnection();
            break;
        }
        catch (IOException)
        {
            _pipeServer.Disconnect();
            continue;
        }            
     }
    
    0 讨论(0)
  • 2021-02-02 11:58

    I had the same problem - it is caused by disposing server's StreamReader by Using...End Using, which also take down NamedPipeServerStream. Solution is simply don't Using...End Using it and trust in garbage collector.

    0 讨论(0)
  • 2021-02-02 12:01

    I'll post my code that seems to work - I was curious since I never did anything with pipes. I didn't find the class you name for the server-side in the relevant namespace, so here's the code based on the NamedPipeServerStream. The callback stuff is just because I couldn't be bothered with two projects.

    NamedPipeServerStream s = new NamedPipeServerStream("p", PipeDirection.In);
    Action<NamedPipeServerStream> a = callBack;
    a.BeginInvoke(s, ar => { }, null);
    ...
    private void callBack(NamedPipeServerStream pipe)
    {
      while (true)
      {
        pipe.WaitForConnection();
        StreamReader sr = new StreamReader(pipe);
        Console.WriteLine(sr.ReadToEnd());
        pipe.Disconnect();
      }
    }
    

    And the client does this:

    using (var pipe = new NamedPipeClientStream(".", "p", PipeDirection.Out))
    using (var stream = new StreamWriter(pipe))
    {
      pipe.Connect();
      stream.Write("Hello");
    }
    

    I can repeat above block multiple times with the server running, no prob.

    0 讨论(0)
提交回复
热议问题