Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2014
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.97 KB | None | 0 0
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. // cancellation by keyboard string
  6. CancellationTokenSource cts = new CancellationTokenSource();
  7.  
  8. // thread that listens for keyboard input
  9. var kbTask = Task.Run(() =>
  10. {
  11. while(true)
  12. {
  13. string userInput = Console.ReadLine();
  14. if(userInput == "c")
  15. {
  16. cts.Cancel();
  17. break;
  18. }
  19. else
  20. {
  21. // handle input
  22. Console.WriteLine("Executing user command {0}...", userInput);
  23. }
  24. }
  25. });
  26.  
  27. // thread that performs main work
  28. Task.Run(() => DoWork(), cts.Token);
  29.  
  30. Console.WriteLine("Type commands followed by 'ENTER'");
  31. Console.WriteLine("Enter 'C' to end program.");
  32. Console.WriteLine();
  33.  
  34. // keep Console running until cancellation token is invoked
  35. kbTask.Wait();
  36. }
  37.  
  38. static void DoWork()
  39. {
  40. while(true)
  41. {
  42. Thread.Sleep(3000);
  43. Console.WriteLine("Doing work...");
  44. }
  45. }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement