I have a process that starts its own thread in it and can be started / stopped without blocking. This will ultimately go into the Windows service, but now I configure it in the console application until it is completely hidden.
After calling Start (), I want the main program flow to be blocked until Ctrl-C is pressed. I know this will work:
public static void Main(string[] args) { bool keepGoing = true; var service = new Service(); System.Console.TreatControlCAsInput = false; System.Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) { e.Cancel = true; service.Stop(); keepGoing = false;
However, I believe that the flag and the arbitrary meaning of sleep are intrusive. I know that the cost of the processor is almost 0 during the while loop, but I would prefer to have a βhardβ block that will be released as soon as the Ctrl-C handler is executed. I developed below using a semaphore to lock until an anonymous Ctrl-C handler is executed:
public static void Main(string[] args) { var service = new Service(); var s = new Semaphore(1, 1); System.Console.TreatControlCAsInput = false; System.Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) { e.Cancel = true; service.Stop(); s.Release();
Is this a bad design? It's too much? This is dangerous?
EDIT:
I also attach AppDomain.CurrentDomain.UnhandledException as follows:
AppDomain.CurrentDomain.UnhandledException += delegate { service.Stop(); s.Release(); };
EDIT 2nd:
I should note that it is very important that the Stop() method be called on exit. @Adam Ralph has a perfectly good hybrid console / service template, but did not have this information in Q's answer.
source share