0

First I write to a NamedPipeClientStream, then I read from it. This basically works. But I don't get the ressource handling of the StreamReader and StreamWriter right.

Approach 1

using (StreamWriter sw = new StreamWriter(pipeStream))
{
  // ...
  using (StreamReader sr = new StreamReader(pipeStream))
  {
    // ...
  }
}

The disposal of sw fails, because the stream has already been closed.

Approach 2

using (StreamWriter sw = new StreamWriter(pipeStream))
{
  // ...
}
using (StreamReader sr = new StreamReader(pipeStream))
{
  // ...
}

Now the pipe server in another process struggles, because the pipe connection was closed prematurely.

Approach 3

In another question regarding file streams it was suggested to use a separate stream for Reader and Writer. But this cannot be applied, since both shall use the same pipe instance.

So how are the streams managed correctly in this situation?

Community
  • 1
  • 1
h0b0
  • 1,802
  • 1
  • 25
  • 44
  • Yes, the StreamReader/Writer.Dispose() method will close the pipe stream. This is rarely what you want, do not use the *using* statement. Neither class has any other resources that require disposing. – Hans Passant Dec 20 '11 at 18:31

1 Answers1

0

Why not use a FileStream that can handle both reading and writing to a single stream?

Andrew Hanlon
  • 7,271
  • 4
  • 33
  • 53