How to keep a .NET console app running?

Posted by intoorbit on Stack Overflow See other posts from Stack Overflow or by intoorbit
Published on 2010-04-06T16:45:57Z Indexed on 2010/04/06 16:53 UTC
Read the original article Hit count: 187

Consider a Console application that starts up some services in a separate thread. All it needs to do is wait for the user to press Ctrl+C to shut it down.

Which of the following is the better way to do this?

static ManualResetEvent _quitEvent = new ManualResetEvent(false);

static void Main() {
    Console.CancelKeyPress += delegate {
        _quitEvent.Set();
    };

    // kick off asynchronous stuff 

    _quitEvent.WaitOne();

    // cleanup/shutdown and quit
}

Or this, using Thread.Sleep(1):

static bool _quitFlag = false;

static void Main() {
    Console.CancelKeyPress += delegate {
        _quitFlag = true;
    };

    // kick off asynchronous stuff 

    while (!_quitFlag) {
        Thread.Sleep(1);
    }

    // cleanup/shutdown and quit
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about multithreading