I have the following code:
public void Dispose()
{
bool append = true;
using(var log = new System.IO.StreamWriter("log.txt", append))
{
log.WriteLine("Disposing");
log.Flush();
}
}
So there’s the risk that the StreamWriter may throw an exception, would that then mean that my object would not get disposed? Would simply wrapping this in a Try/Catch solve the issue?
Thanks.
It depends on what you mean by this:
Your object has had
Disposecalled on it, otherwise it wouldn’t have reached theStreamWritercode. ThatDisposecall may not have completed, but it’s not like there’s some magical flag on an object saying “disposed or not disposed”.Note that disposal is logically separate from garbage collection and finalization: your object will still become eligible for garbage collection in the same way as normal (when there are no live references) and if you have a finalizer (almost certainly not a good idea) it will still be called if you haven’t suppressed it.
It’s important to understand that although C# has support for
IDisposableat the language level, the CLR really doesn’t care about it. It’s just another interface, andDisposeis just another method.In general it’s a bad idea for
Disposeto throw an exception (as if an object is disposed as part of cleaning up an existing failing operation, you end up losing the original exception) but it’s not going to fundamentally damage the CLR in some way.