Hi,
In the following Dispose function, we do not dispose our stream instance if we were called from the finalizer. (yes, I know that this is a somewhat convoluted version of Dispose and it should be protected virtual, but this is the way it's written in the the source I'm referencing, see Essential C# 5.0 link below)
class Foo
{
FileInfo File;
Stream Stream;
// yada yada yada more code goes here...
public void Dispose(bool disposing)
{
if (disposing)
{
if (Stream != null)
{
Stream.Dispose();
}
}
if (File != null)
{
File.Delete();
}
}
}As far as I understand, this is due to unpredictable order of GC release of objects, including instance members.
But, the above code will definitely raise an exception (I tested it) if:
- The client developer forgot to invoke Dispose() directly
- The finalizer invoked Dispose(false)
- Thre stream wasn't disposed yet
So File.Delete() will fail and throw a System.IO.IOException exception.
So my question is, what is the proper way of ensuring that both the stream gets closed and the file gets deleted? (even on the event that the developer forgot to manually dispose the object) Obviously accessing Stream member (while disposing==false) is unsafe, so there's gotta be a way.
Please note that FileOptions.DeleteOnClose is not an option. Here's the motivation: I have a similar class that Open's and Close's some file, and uses the file (i.e. reads data) across method boundaries, and I don't wish to delete the file before the actual end of usage.
Reference: Essential C# 5.0
Thanks,
Ofir