Never ending console app?

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.
 
K

Kristoffer Persson

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 -
 
W

Willy Denoyette [MVP]

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.
 
B

Bob Grommes

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top