为什么终结呼吁对象 [英] Why is finalizer called on object

查看:146
本文介绍了为什么终结呼吁对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是表现出令人惊讶的定稿行为例子程序:

Here is example program that exhibits surprising finalization behavior:

class Something
{
    public void DoSomething()
    {
        Console.WriteLine("Doing something");
    }
    ~Something()
    {
        Console.WriteLine("Called finalizer");
    }
}

namespace TestGC
{
    class Program
    {
        static void Main(string[] args)
        {
           var s = new Something();
           s.DoSomething();
           GC.Collect();
           //GC.WaitForPendingFinalizers();
           s.DoSomething();
           Console.ReadKey();
        }
    }
}

如果我运行该程序,什么会打印为:

If I run the program, what gets printed is:

Doing something
Doing something
Called finalizer

这似乎符合市场预期。因为是调用 GC.Collect的后个引用(),s是不是垃圾。

This appears as expected. Because there is a reference to s after the call to GC.Collect(), s is not a garbage.

现在删除该行注释 // GC.WaitForPendingFinalizers();
构建和运行再次程序

Now remove comments from the line //GC.WaitForPendingFinalizers(); build and run the program again.

我希望没什么可改变输出。这是因为我读如果对象被发现是垃圾,它有一个终结,这将是终结队列把。由于对象不是垃圾,则似乎合乎逻辑的,它不应该在终结队列中放。因此该行注释掉应该什么都不做。

I would expect nothing to change in the output. This because I read that if object is found to be a garbage and it has a finalizer, it will be put on finalizer queue. Since object is not a garbage, then is seems logical that it should not be put on finalizer queue. Thus the line commented out should do nothing.

但是,该程序的输出是:

However, the output of the program is:

Doing something
Called finalizer
Doing something

有人可以帮我为什么终结被称为理解?

Can somebody help my understanding of why finalizer gets called?

推荐答案

我无法重现我的笔记本电脑的问题,而是你的的DoSomething 方法不对象内使用的任何字段。这意味着,该对象可以完成的即使的DoSomething 运行

I can't reproduce the problem on my laptop, but your DoSomething method doesn't use any fields within the object. That means that the object can be finalized even while DoSomething is running.

如果你改变你的代码:

class Something
{
    int x = 10;

    public void DoSomething()
    {
        x++;
        Console.WriteLine("Doing something");
        Console.WriteLine("x = {0}", x);
    }
    ~Something()
    {
        Console.WriteLine("Called finalizer");
    }
}



...然后我怀疑你会的总是的看到 DoingSomething 调用终结前两次印刷 - 虽然最后的X = 12可能会被称为终结之后的印刷

... then I suspect you will always see DoingSomething printed twice before "Called finalizer" - although the final "x = 12" may be printed after "Called finalizer".

基本上,定稿可能有点令人吃惊 - 我的非常的很少能找到自己使用它,并会鼓励你,以避免终结尽可能

Basically, finalization can be somewhat surprising - I very rarely find myself using it, and would encourage you to avoid finalizers wherever possible.

这篇关于为什么终结呼吁对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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