Destructor and thread problem

  • Thread starter Thread starter nicolasr
  • Start date Start date
N

nicolasr

Hi,
I have the following UserControl which creates a thread.
The thread should ideally be created right before the form
which owns the UserControl is shown for the first time
and should get destroyed before the form is destroyed.

The code below is my first try. Problem: the destructor of the
Logger class is never called, the thread is never aborted
and my test program hosting the component hangs when closed.

Can anyone enlighten me why the destructor never gets called and
where to abort the thread correctly?

thanks for any idea,
Nick


using System;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;

namespace Project1
{
class Logger
{
private bool terminate = false;
private Thread logThread;

private void LogThreadStart()
{
MessageBox.Show("Thread started");
while(!terminate)
{
// some log processing here
Thread.Sleep(1000);
}
MessageBox.Show("Thread terminates");
}

public Logger()
{
int i;
logThread = new Thread(new ThreadStart(LogThreadStart));
logThread.Start();
}

~Logger()
{
MessageBox.Show("Entered Logger Destructor");
terminate = true;
if(false == logThread.Join(3000))
logThread.Abort();
}
}

public class UserControl : System.Windows.Forms.UserControl
{
private System.ComponentModel.Container components = null;

private Logger logger;

public UserControl()
{
this.Size = new Size(100, 30);
logger = new Logger();
}

protected override void OnPaint(PaintEventArgs e)
{
//just to make the component visible...
SolidBrush b = new SolidBrush(Color.Yellow);
e.Graphics.FillRectangle(b, ClientRectangle);
base.OnPaint(e);
}
}
}
 
"nicolasr" said:
Hi,
I have the following UserControl which creates a thread.
The thread should ideally be created right before the form
which owns the UserControl is shown for the first time
and should get destroyed before the form is destroyed.

The code below is my first try. Problem: the destructor of the
Logger class is never called, the thread is never aborted
and my test program hosting the component hangs when closed.

Can anyone enlighten me why the destructor never gets called and
where to abort the thread correctly?

These links are a little old, but the concepts still apply:

Garbage Collection: Automatic Memory Management in the .NET Framework
http://msdn.microsoft.com/msdnmag/issues/1100/GCI/GCI.asp
http://msdn.microsoft.com/msdnmag/issues/1200/GCI2/GCI2.asp

What you want to do is make your component support the IDisposable
interface and do your cleanup in the Dispose() method.
 
thanks Jason.
Do you have any idea how to catch this event from within my Component? The
problem is that my component doesn't seem to know about the form, even if
it's placed it. Isn't there something like a Mainform property?

regards,
Nick
 
Back
Top