微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

情况:

>对象变得符合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...)

原文地址:https://www.jb51.cc/csharp/94006.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐