C# Timer control

  • Thread starter Thread starter Frank Mills
  • Start date Start date
F

Frank Mills

Hi,

I have a timer control which writes to a file every 5 seconds but the
application closes down before it gets to the second firing of the
timer. How can i get the application to stay alive until the next timer
interval comes around?

Thanks
 
Hi Frank,

Frank Mills said:
Hi,

I have a timer control which writes to a file every 5 seconds but the
application closes down before it gets to the second firing of the
timer. How can i get the application to stay alive until the next timer
interval comes around?

Thanks

In your timer code, call a method that sets an event if the application is
exiting. Have the UI thread wait for the event before exiting. You can use
ManualResetEvent class as the event class. You can only do this when the
timer is not invoked (synchronized) on the UI thread, so the timer should
execute on another thread. I'll sketch the outline:

<code>
private bool _exitingApp = false;
private object _closingLock = new object();

private ManualResetEvent timerTick = new ManualResetEvent( false );

private bool ExitingApp {
get {
lock( _closingLock )
return _exitingApp;
}
set {
lock( _closingLock )
_exitingApp = value;
}
}

// Timer handler outline, should not be invoked (synchronized) on UI thread
private void TimerCode()
{
// do timer things

ReportTimerTick();
}

private void ReportTimerTick()
{
if( ExitingApp )
timerTick.Set();
}

// form's closing handler
private void OnFormClosing( object sender, FormClosingEventArgs e )
{
ExitingApp = true;

timerTick.WaitOne();
}
</code>

Hope this helps,
Tom T.
 
Back
Top