StreamWriter inside Dispose

2019-08-03 19:14发布

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.

标签: c# dispose
2条回答
再贱就再见
2楼-- · 2019-08-03 20:04

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)

查看更多
老娘就宠你
3楼-- · 2019-08-03 20:06

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.

查看更多
登录 后发表回答