I have a List
. Each Timer fires at a configurable interval (default 10 minutes). All call the same callback method (with a diffe
You could use ManualResetEvents to block the main thread until any pending operations have completed.
for example if you would like all timers to execute at least once then you could have an System.Threading.ManualResetEvent[]
array with the initial state set to non-signalled
So somewhere in your code you would have your timer setup and it's associated waithandle initialised.
// in main setup method..
int frequencyInMs = 600000; //10 mins
Timer timer = new Timer();
timer.Elapsed += (s, e) => MyExecute();
myTimers.Add(timer)
ManualResetEvent[] _waithandles = new ManualResetEvent[10];
_waithandles[0] = new ManualResetEvent(false);
// Other timers ...
timer = new Timer();
timer.Elapsed += (s, e) => MyOtherExecute();
myTimers.Add(timer)
_waithandles[1] = new ManualResetEvent(false);
// etc, and so on for all timers
// then in each method that gets executed by the timer
// simply set ManualReset event to signalled that will unblock it.
private void MyExecute()
{
// do all my logic then when done signal the manual reset event
_waithandles[0].Set();
}
// In your main before exiting, this will cause the main thread to wait
// until all ManualResetEvents are set to signalled
WaitHandle.WaitAll(_waithandles);
If you only wanted to wait for pending operations to finish then simply modify to something like this:
_waithandles[0] = new ManualResetEvent(true); // initial state set to non blocking.
private void MyExecute()
{
_waithandles[0].Reset(); // set this waithandle to block..
// do all my logic then when done signal the manual reset event
_waithandles[0].Set();
}