StreamWriter inside Dispose

2019-08-03 19:30发布

问题:

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.

回答1:

It depends on what you mean by this:

would that then mean that my object would not get disposed?

Your object has had Dispose called on it, otherwise it wouldn't have reached the StreamWriter code. That Dispose 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, and Dispose 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.



回答2:

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?

If StreamWriter will throw exception, only side effect will be that following will not execute.

 log.WriteLine("Disposing");
 log.Flush();

Rest everything will be as expected. StreamWriter will be disposed properly as well. (That is the purpose of using keyword)



标签: c# dispose