I have a method, that takes Stream as parameter:
public void Method(Stream stream)
{
...
}
In this method I create StreamReader. Should I enclouse StreamReader usage in using statement? If so, strea开发者_StackOverflowm will be disposed, that is incorrect. What is the best practise of using Stream and StreamReader in this case?
Nope - in this case it's traditional for the caller to do the disposing.
Calling Dispose
on the StreamReader
will dispose the underlying Stream
. If this is what you want then wrap the StreamReader
in the using
construct. Otherwise just construct the StreamReader
and leave it for the garbage collector to clean up.
In other words, it depends on whether your function is 'taking ownership of' the Stream
.
In such cases, I tend to write something like this and the end of method:
streamWriter.Flush(); // Only for writers, not for readers
streamWriter = null; // Show myself and other coders that lack of Dispose is not a mistake but it's intented
That approach is what I use for stream decorators that always dispose underlying streams, it's worth to mention, that in some cases (for example - DeflateStream
) you need to call .Dispose()
, but in such cases, stream decorators allows you to choose you want them to close underlying stream or not. It might look like this:
DeflateStream deflateStream = new DeflateStream(fileReader.BaseStream, CompressionMode.Decompress, true);
BinaryReader deflateReader = new BinaryReader(deflateStream);
var articleText = deflateReader.ReadString();
deflateReader = null;
deflateStream.Close();
deflateStream.Dispose();
deflateStream = null;
精彩评论