Winform destructor not being called

  • Thread starter Thread starter Martin Hart - Memory Soft, S.L.
  • Start date Start date
M

Martin Hart - Memory Soft, S.L.

Hi:

I'm sure this will be a very simple question to answer, but I can't see the
solution.

I am launching a modal WinForm from my main form via:

using(frmChildForm frm = new frmChildForm())
{
frm.ShowDialog();
}

The frmChildForm class is *very* simple:

public frmChildForm()
{
Trace.WriteLine(">> C'tor frmChildForm");
InitializeComponent();
}

~frmChildForm()
{
MessageBox.Show("This is the destructor");
Trace.WriteLine(">> D'tor frmChildForm");
}

My problem is that the MessageBox (and Trace) never get
called when I close the child form. Why?

TIA,
Martin.
 
Hi Martin Hart - Memory Soft, S.L.,
Hi:

I'm sure this will be a very simple question to answer, but I can't
see the solution.

I am launching a modal WinForm from my main form via:

using(frmChildForm frm = new frmChildForm())
{
frm.ShowDialog();
}

The frmChildForm class is *very* simple:

public frmChildForm()
{
Trace.WriteLine(">> C'tor frmChildForm");
InitializeComponent();
}

~frmChildForm()
{
MessageBox.Show("This is the destructor");
Trace.WriteLine(">> D'tor frmChildForm");
}

My problem is that the MessageBox (and Trace) never get
called when I close the child form. Why?

In .NET there are *no* destructors. There is something which is called
"finalizer".
The finilizer is called from the garbage-collector (maybe from an different
thread) if the GC thinks it should do this. There is *no* deterministic of
doing this. There are cases in which the finailizer will never be called!


If you already using the "using" statement, then you should but your
"destructor" into the Dispose method.


See: IDisposable
http://msdn.microsoft.com/library/en-
us/cpref/html/frlrfSystemIDisposableClassTopic.asp


--
Greetings
Jochen

My blog about Win32 and .NET
http://blog.kalmbachnet.de/
 
Jochen:

Thanks for the interest.

All I am trying to do is print a Trace message to demonstrate that the
object has been destroyed. I realize the side effects in using a destructor
but for my tests this is not a determining factor.

The question remains, why is the destructor never called?

Thanks,
Martin
 
Hi Martin Hart - Memory Soft, S.L.,
All I am trying to do is print a Trace message to demonstrate that the
object has been destroyed. I realize the side effects in using a
destructor but for my tests this is not a determining factor.

The question remains, why is the destructor never called?

The desructor might be called if you terminate the app. But also in this
case it is not guaranteed. And because the runtime is also terminating, the
methods you are executing (which are calling the runtime) are not
successful!

You can force the GC to call pending finalizers with:

GC.Collect();
GC.WaitForPendingFinilizers();
GC.Collect();

--
Greetings
Jochen

My blog about Win32 and .NET
http://blog.kalmbachnet.de/
 
Back
Top