Question

I have a console app that runs some on demand reporting in a webapplication. The app starts, runs some housecleaning, starts a (1 second) timer, and blocks on a Console.ReadLine(); statement. (I've been meaning to stuff it into a service instead, but that's for another day)

Right now this has no exception-handling, so if the sql server it polls against goes down or there is a network hiccup, it just crashes. I'm trying to implement a crude exception-handling now. Inside the timer-callback I have stuffed the sql-query inside a trycatch. If it fails, it handles the exception by logging, increasing a failurecounter and resuming the timer. If it fails more than 5 times I want it to exit the app (sort of) gracefully. How can I force-quit a console app that is blocked with a readline statement?

Code in a gist: https://gist.github.com/cwattengard/11171563

Was it helpful?

Solution

I think a more elegant solution is to block with a reset event. The timer callback sets this at some point when it considers that it no longer has work to do.

static readonly ManualResetEvent reset = new ManualResetEvent(false);

static void Main(string[] args)
{
    var t = new Timer(TimerCallback, null, -1, 1000);
    t.Change(0, 1000);
    reset.WaitOne(); // the application will sit here until the timer tells it to continue.
}

private static void TimerCallback(object state)
{
    try
    { 
       // do stuff.
    }
    catch (Exception e)
    {
        failureCounter++;
        if (failureCounter > 5)
        {
            reset.Set(); // release the reset event and the application will exit,
            return;
        }
    }
}

OTHER TIPS

The best way would be to use some sort of signalling mechanism. For example you start the main thread, do all your initialization (timer etc) then create a non signaled ManualResetEvent and wait on it to fire. If the callback from the timer decides the application should terminate it signals the ManualResetEvent and the main thread is released, completes, and terminates the program...

As a matter of general approach, you should always use signaling and ""cooperative multi-tasking"" within your application. In the sense you signal other threads\ tasks\ actors\ whatever to do stuff, you shouldn't forcefully kill them...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top