Timer Thread does not get disposed

  • Thread starter Thread starter Dipankar
  • Start date Start date
D

Dipankar

In an Windows application I have created a Timer to monitor some
WorkerThread's state. Once the worker thread stops the timer should
also dispose after displaying the message that Worker Thread is done.

// Instance variables
private Thread workerThread = null;
private System.Threading.Timer workerThreadMonitorTimer = null;

/// Code inside a button click event
ThreadStart workerThreadStart = new ThreadStart(DoWork);
this.workerThread = new Thread(migrationProcessStart);
this.workerThread.Start();

TimerCallback timerCallBack = new TimerCallback(CheckWorkerThread);
this.workerThreadMonitorTimer = new
System.Threading.Timer(timerCallBack);
this.workerThreadMonitorTimer.Change(0, 5000);

In the CheckWorkerThread method I wrote:

if (this.workerThread.ThreadState ==
System.Threading.ThreadState.Stopped)
{
// Display some message
this.workerThreadMonitorTimer.Dispose();
}

But the timer does not get disposed. It still executes the
CheckWorkerThread method next time as well. So message is getting
displayed multiple times. Its not even ending.
 
Hi,


Dipankar said:
In an Windows application I have created a Timer to monitor some
WorkerThread's state. Once the worker thread stops the timer should
also dispose after displaying the message that Worker Thread is done.

// Instance variables
private Thread workerThread = null;
private System.Threading.Timer workerThreadMonitorTimer = null;

In a win app you better use System.Windows.Forms.Timer class.
/// Code inside a button click event
ThreadStart workerThreadStart = new ThreadStart(DoWork);
this.workerThread = new Thread(migrationProcessStart);
this.workerThread.Start();

TimerCallback timerCallBack = new TimerCallback(CheckWorkerThread);
this.workerThreadMonitorTimer = new
System.Threading.Timer(timerCallBack);
this.workerThreadMonitorTimer.Change(0, 5000);

Do you want to call it right away? otherwise call it like Change( 5000,
5000)

In the CheckWorkerThread method I wrote:

if (this.workerThread.ThreadState ==
System.Threading.ThreadState.Stopped)

You should also first check if workerThread is null , just as a way to avoid
a nullreference exception
{
// Display some message
this.workerThreadMonitorTimer.Dispose();
}

You should call :
Change( Timeout.Infinite, Timeout.Infinite );
this.workerThreadMonitorTimer.Dispose();
this.workerThreadMonitorTimer = null;
 
Hi,

What is the specific reason of using Forms.Timer rather than
Threading.Timer?
Do these two classes bahave differently?

Cheers!!
Dipankar
 
Back
Top