为什么垃圾收集发生在错误的顺序对象? [英] Why garbage collector takes objects in the wrong order?

查看:157
本文介绍了为什么垃圾收集发生在错误的顺序对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类,A和B.申请A类具有B类的引用中的类的析构函数做资源的一些清理工作,但他们以正确的顺序被调用,先析构函数A和B.随后的析构函数



正在发生的事情是,不知怎的,b的析构函数被调用,然后再A的析构函数崩溃,因为试图执行来自处置对象的方法。



时GC的这种行为是否正确?我预计GC检测A有到B的引用,然后首先调用析构函数。 ?我说的对



感谢队友



PD:大约在析构函数/终结/处置等疑问这就是我们所拥有的:

 〜A()
{
this.Dispose();
}

〜B()
{
this.Dispose();
}


解决方案

的GC是不确定的:它不能保证垃圾收集你的对象在任何特定的顺序,或者在任何时间,甚至永远---它可以决定让他们围绕完成程序后,如果它想。因此终结是非常有用的很少或使用的。



如果你想确定终止,你应该使用的 的IDisposable 模式


I have an application with two classes, A and B. The class A has inside a reference to class B. The destructors of the classes do some cleanup of resources but they have to be called in the right order, first the destructor of A and then the destructor of B.

What is happening is that somehow the destructor of B is called first and then the destructor of A is crashing because is trying to execute methods from a disposed object.

Is this behavior of the GC correct? I expected the GC to detect that A has a reference to B and then call the A destructor first. Am I right?

Thanks mates!

PD: In case of doubt about destructor/finalizer/disposer etc that's what we have:

~A()
{
    this.Dispose();
}

~B()
{
    this.Dispose();
}    

解决方案

The GC is nondeterministic: it is not guaranteed to garbage-collect your objects in any particular order, or at any time, or even ever---it could decide to keep them around after your program is completed, if it wanted to. Thus finalizers are very rarely useful or used.

If you want deterministic finalization, you should use the IDisposable pattern.

这篇关于为什么垃圾收集发生在错误的顺序对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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