I have a class which manages access to a binary file. I want to open this file on first request and then keep it open until the instance of my class gets disposed. I have implemented it like so:
public class SomeService : IDisposable
{
private BinaryReader _reader;
public int ServiceFunction(...)
{
if (_reader == null)
CreateReader();
// Do something with _reader and return a result
}
private void CreateReader()
{
var stream = new FileStream("myFile", FileMode.Open, FileAccess.Read);
_reader = new BinaryReader(stream);
}
public void Dispose()
{
if (_reader != null)
_reader.Dispose();
}
}
I would then use the class this way:
using (var service = new SomeService())
{
foreach (var item in someList)
{
// other stuff
if (eventuallyTrue)
{
int result = service.ServiceFunction(item.SomeProperty);
// other stuff
}
}
}
Questions:
_reader.Dispose() or is it also necessary to dispose the FileStream explicitely?If I need to dispose the FileStream too, can I modify the Dispose method like this:
public void Dispose()
{
if (_reader != null)
{
if (_reader.BaseStream != null)
_reader.BaseStream.Dispose();
_reader.Dispose();
// Does the order of disposing matter here ?
}
}
Or do I need to hold the FileStream in a separate class variable private FileStream _stream and dispose this stream later?
Disposing of the _reader is enough.
But that is because of a peculiar 'feature' of the reader, it assumes ownership of the stream.
So as a general pattern for 2 related or unrelated Disposables it will not do. And therefore I would store the Stream as _stream and Dispose it in the end too, just to be safe and consistent. It certainly won't hurt.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With