Dispose中的StreamWriter [英] StreamWriter inside Dispose

查看:73
本文介绍了Dispose中的StreamWriter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

        public void Dispose()
        {
            bool append = true;
            using(var log = new System.IO.StreamWriter("log.txt", append))
            {
                log.WriteLine("Disposing");
                log.Flush();
            }
        }

因此,存在StreamWriter可能引发异常的风险,那是否意味着我的物品将不被处置?只需将其包装在尝试/捕获中即可解决问题?

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?

谢谢。

推荐答案

这取决于您的意思:


那是否意味着我的物品不会被丢弃?

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

您的对象已调用 Dispose ,否则不会达到 StreamWriter 代码。 Dispose 调用可能尚未完成,但这不像对象上有一个神奇的标志,上面写着已处置或未处置。

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.

重要的是要理解尽管C#支持 IDisposable 在语言级别上,CLR 确实并不关心它。它只是另一个接口,而 Dispose 只是另一种方法。

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.

通常,对于处置引发异常(就像处置对象是清理现有失败操作的一部分一样,您最终会丢失原始异常),但它不会从根本上破坏CLR中的某种方式。

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.

这篇关于Dispose中的StreamWriter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆