Never ending console app?

  • Thread starter Thread starter Jon Skeet [C# MVP]
  • Start date Start date
J

Jon Skeet [C# MVP]

I have a small console app that has a Run method like this:

public void Run()
{
m_Timer = new System.Timers.Timer(1000);
m_Timer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimer);
}

The problem is that the code obiously exits the Run method immediately. What
I want is for my application to do nothing but handle timer events and
recognize when it should be shut down.

Some sort of message loop perhaps?

Well, the easiest thing would be to just Wait on some reference or
other at the end of the Run method, and then when you want to exit the
app, make your timer Pulse the same reference.
 
I have a small console app that has a Run method like this:

public void Run()
{
m_Timer = new System.Timers.Timer(1000);
m_Timer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimer);
}

The problem is that the code obiously exits the Run method immediately. What
I want is for my application to do nothing but handle timer events and
recognize when it should be shut down.

Some sort of message loop perhaps?

- Kristoffer -
 
Kristoffer Persson said:
I have a small console app that has a Run method like this:

public void Run()
{
m_Timer = new System.Timers.Timer(1000);
m_Timer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimer);
}

The problem is that the code obiously exits the Run method immediately.
What
I want is for my application to do nothing but handle timer events and
recognize when it should be shut down.

Some sort of message loop perhaps?

- Kristoffer -

One option is to use an AutoResetEvent.


AutoResetEvent ev;
public void Run()
{
ev = new AutoResetEvent(false);
m_Timer = new System.Timers.Timer(1000);
m_Timer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimer);
ev.WaitOne(); //wait for event to be signaled
}

void OnTimer(...)
{
....
if(timeToExitProgram == true)
ev.Set(); //Signal event
....

}

Willy.
 
Or, use ReadLine and then check for a very deliberate entry such as QUIT or
STOP RIGHT NOW or whatever.

In the long run, an application like this, once tested, should probably be
turned into a Windows Service.

--Bob
 
Back
Top