0

I have what is currently a single-threaded console app which does something every 30s... e.g.

while(exitFlagNotSet)
{
 doStuff();
 Thread.Sleep(30000);
}

However I'd also like to listen for application-exit a bit along the lines of Capture console exit C#. In such a situation I can't wait 30s - my app will be forcibly terminated after 5s IIRC.

So is there a way to refactor my approach so the 30s wait may be aborted when something occurs? I've done this kind of thing in C++ but don't know what the terminology and techniques are in C#/.net

Community
  • 1
  • 1
Mr. Boy
  • 60,845
  • 93
  • 320
  • 589

1 Answers1

1

You can use WaitHandle of CancellationToken to do that:

static void Main(string[] args) {
    var cts = new CancellationTokenSource();
    var token = cts.Token;
    EventHandler handler = new EventHandler(sig => {
        // may want to investigate signal here
        // cancel if appropriate
        cts.Cancel();
        return true;
    });
    // this is from your linked answer
    SetConsoleCtrlHandler(handler, true);

    while (!cts.IsCancellationRequested) {
        Console.WriteLine("doing stuff");
        var cancelled = token.WaitHandle.WaitOne(30000);
        if (cancelled) {
            // handle exit
            Console.WriteLine("Cancelled!");
            break;
        }
    }
}

When calncelled - WaitHandle of CancellationToken will be signalled, and as such WaitOne returns true. If WaitOne exited because of timeout - it returns false.

Evk
  • 98,527
  • 8
  • 141
  • 191
  • I don't know if this is correct but in my tests I did `while(!cts.IsCancellationRequested)` which made things more elegant – Mr. Boy Jun 02 '16 at 15:37
  • @MrBoy sure, that's just example of how to wait until timeout or cancelled, while (true) is not relevant. – Evk Jun 02 '16 at 16:22