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.
If StreamWriter will throw exception, only side effect will be that following will not execute.
Rest everything will be as expected. StreamWriter will be disposed properly as well. (That is the purpose of
using
keyword)It depends on what you mean by this:
Your object has had
Dispose
called on it, otherwise it wouldn't have reached theStreamWriter
code. ThatDispose
call 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
IDisposable
at the language level, the CLR really doesn't care about it. It's just another interface, andDispose
is just another method.In general it's a bad idea for
Dispose
to 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.