首页 新闻 会员 周边

C#中内存回收问题

0
[已关闭问题] 关闭于 2012-10-19 10:05
class Destruct
{
  public int x;
  public Destruct(int i)
  {
    x = i;
  }
  ~Destruct()
  {
    Console.WriteLine(x);
  }

  public void Generator(int i)
  {
    Destruct o = new Destruct(i);
  }
}


class Program
{
  static readonly Int32 number = 10;

  static void Main(string[] args)
  {
    int count = 0;
    Console.WriteLine("Hello World");

    Destruct ob = new Destruct(0);
    for (count = 1; count < 200000; count++)
    {
      ob.Generator(count);
    }
    Console.WriteLine("Done");

}

环境为VS2010。
这个程序运行时,输出总是
Done
199999
0
199998
.
.
1
为什么总是最后一个Generator函数创建的对象被先释放,然后是ob被释放,然后才按顺序释放Generator创建的对象,怎么解释。

C#
冰呆瓜的主页 冰呆瓜 | 菜鸟二级 | 园豆:202
提问于:2012-10-17 15:49
< >
分享
所有回答(2)
0

finalize的调用是由GC控制滴。

Ethan轻叹 | 园豆:996 (小虾三级) | 2012-10-17 16:06
0

对象的回收没有一个严格固定的顺序,只有大概的规则(比如0代>1代等)。对于同一代中的对象,顺序不能够确定(而且也没有什么官方文档明确过这个顺序)。你把你代码中的count修改一下,或者换个环境运行你的代码,结果都有可能不同。

水牛刀刀 | 园豆:6350 (大侠五级) | 2012-10-17 19:39

不是,这个顺序是确定的,不管数字换成多少,比如20,一定是19,0,18....1。

支持(0) 反对(0) 冰呆瓜 | 园豆:202 (菜鸟二级) | 2012-10-18 11:36

@冰呆瓜: 那是你的机器。其他人就未必。

支持(0) 反对(1) 水牛刀刀 | 园豆:6350 (大侠五级) | 2012-10-18 12:33
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册