C# 垃圾收集器复活 Null Ref 异常

标签 c# garbage-collection

我有这段代码(用于一个非常好的和友好的网站)

public class B
{
    static public A IntA;
}

public class A
{
    private int x;

    public A(int num)
    {
        x = num;
    }

    public void Print()
    {
        Console.WriteLine("Value : {0}", x);
    }

    ~A()
    {
        B.IntA = this;
    }
}

class RessurectionExample
{
    // Ressurection
    static void Main()
    {
        // Create A instance and print its value
        A a = new A(50);
        a.Print();

        // Strand the A object (have nothing point to it)
        a = null;

        // Activate the garbage collector
        GC.Collect();

        // Print A's value again
        B.IntA.Print();
    }
}

它创建一个值为 50 的 A 实例,打印它,通过将他的唯一引用设置为空来将创建的对象串起来,激活他的 Dtor 并在保存在 B 之后 - 再次打印它。

现在,奇怪的是,在调试时,当光标指向最后一行(B.IntA.Print())时,静态 A 成员的值为 null,按 F10 后,我得到一个 NullReferenceException BUT静态 A 成员的值更改为应有的值。

谁能解释一下这个现象?

最佳答案

您需要调用 GC.WaitForPendingFinalizers .否则,您的析构函数实际上不会按顺序调用。

static void Main()
{
    // Create A instance and print its value
    A a = new A(50);
    a.Print();

    // Strand the A object (have nothing point to it)
    a = null;

    // Activate the garbage collector
    GC.Collect();

    // Add this to wait for the destructor to finish
    GC.WaitForPendingFinalizers();

    // Print A's value again
    B.IntA.Print();
}

关于C# 垃圾收集器复活 Null Ref 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11906984/

相关文章:

c# - 如何在 C# 中使用线程一次发送多个 Web 请求?

c# - 如何在 NHibernate 中创建表示两个 EXISTS 之间的 OR 的条件?

c# - 线程化对象中包含的方法 - C#

java - 为 PhantomReference 应用程序创建可重复的测试

java - 如果只有迭代器存在,List 会被垃圾回收吗

c# - 无法使用 https 获取网络响应

c# - 使用 FedEx 运送服务 WSDL 创建 FedEx 运送文件

java - 是-XX :+UseG1GC the correct replacement for -Xincgc?

python - 在 Python 中 : How to remove an object from a list if it is only referenced in that list?

java - 在重写的finalize()方法中关闭类IO资源