C# 垃圾收集器生成不递增
我对垃圾收集过程有很多疑问,主要是它何时运行,对象何时设置为较旧的一代,等等C# 垃圾收集器生成不递增,c#,.net,garbage-collection,C#,.net,Garbage Collection,我对垃圾收集过程有很多疑问,主要是它何时运行,对象何时设置为较旧的一代,等等 static void Main(string[] args) { int i = 0, j = 0; int a = 0; Holder prev = new Holder(null); while(GC.CollectionCount(1) == 0) { int aux = GC.CollectionCount(0); if(aux &g
static void Main(string[] args)
{
int i = 0, j = 0;
int a = 0;
Holder prev = new Holder(null);
while(GC.CollectionCount(1) == 0)
{
int aux = GC.CollectionCount(0);
if(aux > a){
a = aux;
++j;
Console.WriteLine((i+1));
}
++i;
Holder h = new Holder(prev);
Console.WriteLine(GC.GetGeneration(prev));
prev = h;
}
}
我正在尝试获取gen1中对象的数量。
为什么j=1代码>??GC在gen0上只运行一次(要离开,它不应该至少运行两次吗)
[编辑]
在休息后加上这个,我感到很困惑
Console.WriteLine(#gc0=“+GC.CollectionCount(0));-->2.
Console.WriteLine(#gc1=“+GC.CollectionCount(1));-->1.
Console.WriteLine(“#objs=“+i”);
Console.ReadLine()代码>
为什么GC.CollectionCount(0)只有2?我一直在通过c#阅读里氏clr,他是这么说的
将检查第1代中的对象
只有当第1代达到其预算时,这通常需要对
第0代
[编辑]
但同时,如果gc看到所有对象都存活下来,它会增长g0极限,这可能是g0上只有2个gc的原因吧?我们用一些随机性来增加一些效果怎么样:
class Program
{
static void Main(string[] args)
{
Random random = new Random();
int i = 0, j = 0;
int a = 0;
Holder prev = new Holder(null);
Holder prev2 = new Holder(null);
while (GC.CollectionCount(1) == 0)
{
int aux = GC.CollectionCount(0);
if (aux > a)
{
a = aux;
++j;
Console.WriteLine((i + 1));
}
++i;
var flag = random.Next(1) == 1;
Holder h = new Holder(flag ? prev : prev2);
Console.WriteLine("Prev: " + GC.GetGeneration(prev));
Console.WriteLine("Prev2: " + GC.GetGeneration(prev2));
if (flag)
{
prev = h;
}
else
{
prev2 = h;
}
}
}
}
internal class Holder
{
private Holder holder;
public Holder(Holder o)
{
holder = o;
}
}
您提供的代码示例非常简单,CLR知道将prev
项移动到另一代没有意义。
它的使用很简单,我认为运行时已经对它进行了优化,使它只在G0上运行
添加更复杂的逻辑会破坏运行时的优化,现在,prev
或prev1
中的一个将出现在G1上,具体取决于使用频率较低的对象(这里不知道确切的机制)
您可以尝试添加prev
和prev2
而不是prevs
数组,然后在索引上进行随机操作,您可以更好地看到数组元素将如何推进生成