code_junkie

How can I keep a console open until CancelKeyPress event is fired?

Nov 11th, 2011
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. class Program
  2. {
  3.  
  4. private static bool _s_stop = false;
  5.  
  6. public static void Main(string[] args)
  7. {
  8. Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
  9. while (!_s_stop)
  10. {
  11. /* put real logic here */
  12. Console.WriteLine("still running at {0}", DateTime.Now);
  13. Thread.Sleep(3000);
  14. }
  15. Console.WriteLine("Graceful shut down code here...");
  16.  
  17. //don't leave this... demonstration purposes only...
  18. Console.ReadLine();
  19. }
  20.  
  21. static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
  22. {
  23. //you have 2 options here, leave e.Cancel set to false and just handle any
  24. //graceful shutdown that you can while in here, or set a flag to notify the other
  25. //thread at the next check that it's to shut down. I'll do the 2nd option
  26. e.Cancel = true;
  27. _s_stop = true;
  28. Console.WriteLine("CancelKeyPress fired...");
  29. }
  30.  
  31. }
Add Comment
Please, Sign In to add comment