加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如果在析构函数中创建对象的活动引用?

发布时间:2020-12-15 03:42:26 所属栏目:百科 来源:网络整理
导读:情况: 对象变得符合GC标准 GC开始收集 GC调用析构函数 在析构函数中,例如,将当前对象添加到静态集合中 在收集对象的过程中,不符合GC的资格,将来会有资格,但在规范中说,Finalize只能被调用一次. 问题: 将对象摧毁? 将会在下一个GC上完成调用? 解决方法 该
情况:

>对象变得符合GC标准
> GC开始收集
> GC调用析构函数
>在析构函数中,例如,将当前对象添加到静态集合中

在收集对象的过程中,不符合GC的资格,将来会有资格,但在规范中说,Finalize只能被调用一次.

问题:

将对象摧毁?
将会在下一个GC上完成调用?

解决方法

该对象不会被垃圾回收 – 但是下一次它有资格进行垃圾收集时,终结器将不再运行,除非您调用 GC.ReRegisterForFinalize.

示例代码:

using System;

class Test
{
    static Test test;

    private int count = 0;

    ~Test()
    {
        count++;
        Console.WriteLine("Finalizer count: {0}",count);
        if (count == 1)
        {
            GC.ReRegisterForFinalize(this);
        }
        test = this;
    }

    static void Main()
    {
        new Test();
        Console.WriteLine("First collection...");
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine("Second collection (nothing to collect)");
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Test.test = null;
        Console.WriteLine("Third collection (cleared static variable)");
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Test.test = null;
        Console.WriteLine("Fourth collection (no more finalization...)");
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

输出:

First collection...
Finalizer count: 1
Second collection (nothing to collect)
Third collection (cleared static variable)
Finalizer count: 2
Fourth collection (no more finalization...)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读