特殊情况寿命分析

Tho*_*ing 11 c# garbage-collection

假设我有

void foo () {
    Bar bar = new Bar(); // bar is never referred to after this line
    // (1)
    doSomethingWithoutBar();
}
Run Code Online (Sandbox Code Playgroud)

在(1),对象bar是否指向有资格进行垃圾收集?或者也bar必须超出范围?如果GC.Collect被调用它会有所作为doSomethingWithoutBar吗?

这与知道Bar是否有(C#)析构函数或类似的类似内容有关.

Mar*_*ers 8

只要确定不再使用对象,对象就有资格进行垃圾回收.完全有可能bar在变量超出范围之前进行垃圾收集.

证明:

using System;

class Bar
{
    ~Bar() { Console.WriteLine("Finalized!"); }
}

class Program
{
    static void Main(string[] args)
    {
        Bar bar = new Bar();
        GC.Collect();
        GC.WaitForPendingFinalizers();
        Console.WriteLine("Press any key to exit...");
        Console.ReadLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

发布模式下运行(因为它不会在调试模式下收集).

输出:

Finalized!
Press any key to exit...

它也适用于使用Mono的ideone.输出是一样的.