Reputation: 3
When using Named Pipes with c#. If we use a using statement to create the client and server pipe, then connect a streamReader and streamWriter to it. Does the streamReader and StreamWriter also get disposed when the namedPipe gets disposed (at the end of the using statement)?
Upvotes: 0
Views: 697
Reputation: 36852
No. Streams do not magically keep track of every StreamReader
or StreamWriter
instance that use them. This is true of any stream, not just named pipes.
var stream = ...;
var reader = new StreamReader(stream);
stream.Dispose();
// reader is not disposed here
However, by default, disposing a StreamReader
or StreamWriter
disposes the stream they were constructed with:
var stream = ...;
using(var reader = new StreamReader(stream))
// ...
// stream is disposed here
That is, unless you constructed them by passing true
to their leaveOpen
parameter (that's the last one, below):
var stream = ...;
using(var reader = new StreamReader(stream, encoding, false, 4096, true))
// ...
// stream is not disposed here
In other words, by default, readers or writers own their streams, which means they are responsible for closing them when they are themselves closed. Readers and writers that do not own their stream will only flush their internal buffers when disposed, but leave the stream otherwise untouched.
Upvotes: 1