它是安全访问引用类型成员变量的终结? [英] Is it safe to access a reference type member variable in a finalizer?

查看:126
本文介绍了它是安全访问引用类型成员变量的终结?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在换句话说,

 类Foo
{
    obj对象;
    富(){OBJ =新的对象(); }
    〜富(){obj.ToString(); / *的NullReferenceException? * /}
}
 

解决方案

这不是安全的,因为OBJ可能已经被垃圾回收。另外请注意,垃圾收集器不会将引用设置为null。因此,即使检查的obj!= NULL不会帮你。

在这里看到的细节: <一href="http://msdn.microsoft.com/en-us/magazine/cc163392.aspx#S3">http://msdn.microsoft.com/en-us/magazine/cc163392.aspx#S3

泛化这一原则,在Dispose方法是安全的清理对象持有到所有资源,无论是管理对象或本机资源。然而,在终结它是唯一安全的清理不属于终结,和一般的终结只能释放本地资源的对象。(您obj是终结,所以你不应该去碰它在另一个终结)

这也是为什么你有

如果(处置){...}

在IDisposable模式(参见图2中上面的链接)。

In other words,

class Foo
{
    object obj;
    Foo() { obj = new object(); }
    ~Foo() { obj.ToString(); /* NullReferenceException? */ }
}

解决方案

It's not safe since obj might have already been garbage collected. Also note that the garbage collector will not set the reference to null. So even checking for obj != null will not help you.

See here for details: http://msdn.microsoft.com/en-us/magazine/cc163392.aspx#S3

"Generalizing this principle, in a Dispose method it’s safe to clean up all resources that an object is holding onto, whether they are managed objects or native resources. However, in a finalizer it is only safe to clean up objects that are not finalizable, and generally the finalizer should only be releasing native resources." (Your obj is finalizable, so you shouldn't touch it in another finalizer)

That's also the reason why you have the

if (disposing) {...}

in the IDisposable pattern (see Figure 2 in the link above).

这篇关于它是安全访问引用类型成员变量的终结?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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