views:

332

answers:

2

Given a System.Timers.Timer, is there a way from the main thread to tell if the worker thread running the elapsed event code is still running?

In other words, how can one make sure the code running in the worker thread is not currently running before stopping the timer or the main app/service thread the timer is running in?

Is this a matter of ditching Timer for threading timer using state, or is it just time to use threads directly?

A: 

For the out of the box solution, there is no way. The main reason is the thread running the TimerCallback function is in all likelihood still alive even if the code running the callback has completed. The TimerCallback is executed by a Thread out of the ThreadPool. When the task is completed the thread does not die, but instead goes back into the queue for the next thread pool task.

In order to get this to work your going to have to use a manner of thread safe signalling to detect the operation has completed.

Timer Documentation

JaredPar
+1  A: 

Look up ManualResetEvent, as it is made to do specifically what you're asking for.

Your threads create a new reset event, and add it to an accessible queue that your main thread can use to see if any threads are still running.

// main thread owns this
private List<ManualResetEvent> _resetEvents;
...
// main thread does this to wait for executing threads to finish
WaitHandle.WaitAll(_resetEvents.ToArray(), 2000, false)
...
// worker threads do this to signal the thread is done
myResetEvent.Set();

I can give you more sample code if you want, but I basically just copied it from the couple articles I read when I had to do this a year ago or so.


Forgot to mention, you can't add this functionality to the default threads you'll get when your timer fires. So you should make your timer handler be very lean and do nothing more than prepare and start a new worker thread.

...
ThreadPool.QueueUserWorkItem(new WaitCallback(MyWorkerDelegate),
  myCustomObjectThatContainsAResetEvent);
sliderhouserules
Wow. It really was that easy. Thanks!
claco