所以GC.Collect()不会立即收集? [英] GC.Collect() not collecting immediately?
问题描述
在聊天讨论的过程中,我写了这个控制台应用程序
代码:
使用系统;
类节目
{
静态无效的主要(字串[] args)
{
CreateClass();
Console.Write(收集...);
GC.Collect的();
Console.WriteLine(完成);
}
静态无效CreateClass()
{
SomeClass的C =新SomeClass的();
}
}
类SomeClass的
{
〜SomeClass的()
{
抛出新的异常();
}
}
结果:
<预类=郎无prettyprint-覆盖>
采集...完成
未处理的异常:System.Exception的:类型的异常'System.Exception的'是
抛出。
在SomeClass.Finalize()
我本来期望应用崩溃的前的完成
印。
我不那么在意如何做到这一点。我的问题是,为什么不呢?
与终结对象不能内收集单垃圾收集过程。这些对象被移动到 F-可达
队列,并保持在那里,直到终结被调用。 。只有这样他们可以是垃圾收集
下面的代码是好,但你不应该反正依靠它:
GC.Collect的();
GC.WaitForPendingFinalizers();
GC.Collect的();
此外,扔在终结例外,似乎对我来说太残酷,即使是用于测试目的。
另外,终结的有趣的副作用:与终结的对象还是可以复活本身(有效防止自身垃圾收集),如果卖场这个
在终结引用(它分配给一些静态变量)。
In the course of a discussion in chat, I wrote this console application.
Code:
using System;
class Program
{
static void Main(string[] args)
{
CreateClass();
Console.Write("Collecting... ");
GC.Collect();
Console.WriteLine("Done");
}
static void CreateClass()
{
SomeClass c = new SomeClass();
}
}
class SomeClass
{
~SomeClass()
{
throw new Exception();
}
}
Result:
Collecting... Done
Unhandled Exception: System.Exception: Exception of type 'System.Exception' was
thrown.
at SomeClass.Finalize()
I would have expected the app to crash before Done
was printed.
I don't care much about how to make it. My question is, why doesn't it?
Objects with finalizers cannot be collected within a single garbage collection procedure. Such objects are moved to f-reachable
queue, and remain there until finalizers are called. Only after that they can be garbage-collected.
Following code is better, but you should not rely on it anyway:
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Also, throwing exceptions in finalizer seems too brutal for me, even for testing purposes.
Also, interesting side-effect of finalizers: an object with finalizer can still 'resurrect' itself (effectively prevent garbage collection of itself), if stores this
reference in finalizer (assigns it to some static variable).
这篇关于所以GC.Collect()不会立即收集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!