gpt4 book ai didi

.net - .net object = null game 何时用于垃圾收集?范围重要吗?

转载 作者:行者123 更新时间:2023-12-04 22:01:03 25 4
gpt4 key购买 nike

各位,

如果我在长时间运行的方法(不一定是 CPU 密集型……只是长时间运行)中间将一个大对象设置为 .net 为 null 是它立即进行垃圾收集游戏还是该方法需要在对象之前完成准备好进行垃圾收集了吗?

最佳答案

该方法不需要完成,但您也不需要将变量设置为 null,如果 GC 可以告诉您不会再次读取它。例如:

public void Foo()
{
SomeObject x = new SomeObject();
// Code which uses x

Console.WriteLine("Eligible for collection");

// Code which doesn't use x.
}

该对象有资格在指定的点收集 - 当然,假设没有其他任何东西保留对它的引用。重要的是是否有任何东西能够再次读取该值。您甚至可以为变量分配一个不同的值然后读取它,只要 GC 知道它不会再次看到原始值,它就不会充当 GC 根。例如:
using System;

class Bomb
{
readonly string name;

public Bomb(string name)
{
this.name = name;
}

~Bomb()
{
Console.WriteLine(name + " - going boom!");
}

public override string ToString()
{
return name;
}
}

class Test
{
static void Main()
{
Bomb b = new Bomb("First bomb");
Console.WriteLine("Using bomb...");
Console.WriteLine(b);
Console.WriteLine("Not using it any more");

GC.Collect();
GC.WaitForPendingFinalizers();

Console.WriteLine("Creating second bomb...");
b = new Bomb("Second bomb");
Console.WriteLine("Using second bomb...");
Console.WriteLine(b);
Console.WriteLine("End of main");
}
}

输出:
Using bomb...
First bomb
Not using it any more
First bomb - going boom!
Creating second bomb...
Using second bomb...
Second bomb
End of main
Second bomb - going boom!

事实上,它可以变得更极端:一个对象可以有资格进行垃圾回收,即使一个方法正在“内部”运行,只要 GC 可以检测到没有任何东西可以再次读取一个字段。这是一个简短但完整的示例:
using System;

class Bomb
{
int x = 10;

~Bomb()
{
Console.WriteLine("Boom!");
}

public void GoBang()
{
Console.WriteLine("Start of GoBang");
GC.Collect();
GC.WaitForPendingFinalizers();

Console.WriteLine("x={0}", x);
Console.WriteLine("No more reads of x");
GC.Collect();
GC.WaitForPendingFinalizers();

Console.WriteLine("Returning");
}
}

class Test
{
static void Main()
{
Bomb b = new Bomb();
b.GoBang();
Console.WriteLine("Still in Main");
}
}

输出:
Start of GoBang
x=10
No more reads of x
Boom!
Returning
Still in Main

(不要在调试器中运行它 - 调试器会延迟垃圾回收,以便您仍然可以观察变量。)

需要注意的一点:您的问题涉及将对象设置为 null ......这个概念不存在。您只将变量设置为 null。值得区分两者。

关于.net - .net object = null game 何时用于垃圾收集?范围重要吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4660445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com