1

Firstly,

thanks someone can help me answer this question, really in my heart~ thanks

currently I am learn something about Gc in c#, do some test

code there

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...");
        }

    }
}

scenario one

when I press button1 to new some object, then call Gc.Collect(); but nothing happen(I expect MessageBox will show 4 times)

when I press button2 secondly ,MessageBox show...(I am confused)

do some one can explain it? (thanks)

scenario two

code here

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...");
        }

    }
}

when I press button1 then press button2 the MessageBox show.....

Frank.Liu
  • 79
  • 5

0 Answers0