C# Gabbage Collecting System

时间:2023-03-09 00:31:59
C# Gabbage Collecting System

* 这个程序非常巧妙的探测了一下垃圾回收机制,发现如下结论:
 * 当内存紧急时,才会启动垃圾回收GC.Collect()
 * 从此程序的运行上来看,delete是连续出现的,这体现了垃圾回收的强度。
 * new haha()这种东西确实是垃圾,会被回收的(除非它有timer,这个对象被另一个线程占用)

using System;
using System.Windows.Forms;
using System.Threading;
class haha
{
    int[] a=new int[10000000];
    haha()
    {
        Console.WriteLine("created");
    }
    void run()
    {
        Console.WriteLine("i am running");
    }
    ~haha()
    {
        Console.WriteLine("deleted");
    }
    static void Main(){
        for (int i = 0; i < 100; i++)
        {
            new haha().run();
            GC.Collect();
        }
        Application.Run();
    }
}

If something is running a thread,the GC cannot collect it.

 using System;
 using System.Windows.Forms;
 class haha
 {
     Timer t = new Timer();
     public haha()
     {
         t.Interval = ;//timer 时间间隔
         t.Tick += run;//每次触发的事件
         t.Start();//开始timer
     }
     void run(object o,EventArgs e)
     {
         Console.WriteLine(DateTime.Now);
     }
 }
 class me
 {
     static void Main()
     {
         new haha();//这个对象始终无法消灭,这个问题就像薛定谔的猫一样,无法观测,看之则有,不看则无。
         Application.Run(new Form());
     }
 }
 /*
  很久之后我才明白:
  * 如果一个对象正在运行,垃圾回收机制就不会收他;
  * 只有停止与此对象相关的一切线程、引用,这个对象才会被视作垃圾
  * 在这里Dispose一下就好了,但是这不是用于Form.timer,只适用于另两个timer。详见“c#中的三个timer”
  */