Object destroying problem...

  • Thread starter Thread starter Roman S. Golubin1709176985
  • Start date Start date
R

Roman S. Golubin1709176985

Hello everybody!

I wrote an project with one class (Class) and two forms (Form1, Form2):

-----------------------------------Form2AndClass1Begin----------------------
------------------
public class Class
{
public void Form2_Closed(object sender, System.EventArgs e)
{
((Form2)sender).Closed -= new System.EventHandler(Form2_Closed);
}
~Class()
{
System.Windows.Forms.MessageBox.Show("~Class destroyed");
}
}

public class Form2 : System.Windows.Forms.Form
{
.....
}

-----------------------------------Form2AndClass1End------------------------
----------------

and application form Form1:

-----------------------------------Form1Begin-------------------------------
---------
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
....
private void button1_Click(object sender, System.EventArgs e)
{
Form2 frm = new Form2();
Class cls = new Class();
frm.Closed += new System.EventHandler(cls.Form2_Closed);
frm.Show();
frm = null;
cls = null;
}
[STAThread]
static void Main()
{
System.Windows.Forms.Application.Run(new Form1());
}
}
}
-----------------------------------Form1End---------------------------------
-------

After Application starts and I Click on button1, then close Form2, then
objects Form2 and Class1 must be disposed and destroyed automatically
(project don't have any reference on its at this time!!!)??!!

Say me, please, why objects Form2 and Class1 destroyed periodically - from
time to time??
 
Hi, Roman
After Application starts and I Click on button1, then close Form2, then
objects Form2 and Class1 must be disposed and destroyed automatically
(project don't have any reference on its at this time!!!)??!!

Say me, please, why objects Form2 and Class1 destroyed periodically - from
time to time??

It takes time until GC collects the non-referenced objects. In your case it
will take even 2 passes until the memory gets reclaimed.
In the first pass Class1 finalizer will be called and at this point Form1
and Class1 will become ready for garbage collecting. The actual collection
will take place during the second pass.
If you try this in a simple test project GC may not occur unless you close
the application.

HTH
B\rgds
100
 
Back
Top