gpt4 book ai didi

c# - 析构函数执行顺序?

转载 作者:行者123 更新时间:2023-11-30 13:36:45 24 4
gpt4 key购买 nike

我知道c#中的析构函数没有执行顺序。

我在几个类中确实使用了以下结构,它用于破坏实例和静态信息:

public class MyClass
{
private static readonly Destructor DestructorObject = new Destructor();

~MyClass()
{
Console.WriteLine("Destructor Called");
}

static void Main(string[] args)
{
var myClass = new MyClass();
}

private sealed class Destructor
{
~Destructor()
{
Console.WriteLine("Static Destructor Called");
}
}
}

正如我上面提到的,析构函数的顺序是不确定的。但是当我在许多类中使用此构造时,我发现在每个类中都有一个不变的顺序,即使我重新编译应用程序并再次运行它也会保持不变。

意味着 MyClass1 总是可以先运行 ~MyClass1 而另一个类 MyClass2 总是可以运行 ~Destructor首先。

既然每个类(class)都有一个“隐藏”的顺序,我能相信吗?

最佳答案

As there clearly is a "hidden" order for each class, can I trust it?

不,你不能。如果您查看 the docs ,他们尖叫:

The finalizers of two objects are not guaranteed to run in anyspecific order, even if one object refers to the other. That is, ifObject A has a reference to Object B and both have finalizers, ObjectB might have already been finalized when the finalizer of Object Astarts.

依赖这样的实现细节作为正常执行流程的一部分将是一个非常糟糕的主意。

看到出于某种原因您选择使用终结器作为清理静态资源的方式,您应该首先考虑这是否是正确的方法,taking into account everything destructors imply ,然后至少实现IDisposable 并为调用者提供释放资源的机会,同时调用GC.SupressFinalize

在你的对象中使用这个作为一个通用方法也会导致对象延长它们的生命,因为它们只有在移动到 f-reachable 队列后才有资格被收集,并且依赖于终结器线程来实际清理它们向上,这根本不能保证。

Eric Lippert 最近 (18-05-2015) 开始了一个名为 When everything you know is wrong 的系列谈论终结器神话,我建议你看一看。

编辑:

埃里克斯很有趣 second post (今天发布)在系列中回答了这个问题:

Myth: Finalizers run in a predictable order

Suppose we have a tree of objects, all finalizable, and all on the finalizer queue. There is no requirement whatsoever that the tree be finalized from the root to the leaves, from the leaves to the root, or any other order.

关于c# - 析构函数执行顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30368849/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com