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.

 1 using System;
 2 using System.Windows.Forms;
 3 class haha
 4 {
 5     Timer t = new Timer();
 6     public haha()
 7     {
 8         t.Interval = 2000;//timer 时间间隔
 9         t.Tick += run;//每次触发的事件
10         t.Start();//开始timer
11     } 
12     void run(object o,EventArgs e)
13     { 
14         Console.WriteLine(DateTime.Now);
15     }
16 }
17 class me
18 {
19     static void Main()
20     {
21         new haha();//这个对象始终无法消灭,这个问题就像薛定谔的猫一样,无法观测,看之则有,不看则无。
22         Application.Run(new Form());
23     }
24 }
25 /*
26  很久之后我才明白:
27  * 如果一个对象正在运行,垃圾回收机制就不会收他;
28  * 只有停止与此对象相关的一切线程、引用,这个对象才会被视作垃圾
29  * 在这里Dispose一下就好了,但是这不是用于Form.timer,只适用于另两个timer。详见“c#中的三个timer”
30  */
原文地址:https://www.cnblogs.com/weiyinfu/p/4936484.html