c#关于GC.Collect()测试

时间:2017-10-11 08:28:57

标签: c# garbage-collection

首先,

谢谢有人可以帮我回答这个问题,真的在心里〜谢谢

目前我正在了解c#中的Gc,做一些测试

那里的代码

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Person p = new Person();
            Person p1 = new Person();
            Person p2 = new Person();
            Person p3 = new Person();
            GC.Collect();
        }

    }

    public class Person
    {
        ~Person()
        {
            MessageBox.Show("destructor has call...");
        }

    }
}
方案一

当我按下button1到新的某个对象时,然后调用Gc.Collect(); 但没有任何事情发生(我希望MessageBox会显示4次)

当我第二次按下按钮2时,MessageBox显示......(我很困惑)

有人可以解释一下吗? (感谢)

场景二

代码

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Person p = new Person();
            Person p1 = new Person();
            Person p2 = new Person();
            Person p3 = new Person();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            GC.Collect();
        }
    }

    public class Person
    {
        ~Person()
        {
            MessageBox.Show("destructor has call...");
        }

    }
}

当我按下按钮1然后按下按钮2 MessageBox show .....

0 个答案:

没有答案