System.Threading.Timer Example


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. using System;
  2. using System.Threading;
  3.  
  4. class Program
  5. {
  6. static void Main()
  7. {
  8. AutoResetEvent reset = new AutoResetEvent(false);
  9. StatusChecker status = new StatusChecker(5);
  10.  
  11. // Invoke methods for the timer via a Delegate
  12. TimerCallback timerDelegate = new TimerCallback(status.CheckStatus);
  13.  
  14. // Create a timer that signals the delegate to invoke
  15. // Check status after one second, and then every 1/4 second
  16. Console.WriteLine("{0} Creating the timer.\n",DateTime.Now.ToString("h:mm:ss.fff"));
  17. Timer stateTimer = new Timer(timerDelegate, reset, 1000, 250);
  18.  
  19. // When the auto reset executes, change to every 1/2 second
  20. reset.WaitOne(5000, false);
  21. stateTimer.Change(0, 500);
  22. Console.WriteLine("\nChanging the timer period.\n");
  23.  
  24. reset.WaitOne(5000, false);
  25. stateTimer.Dispose();
  26. Console.WriteLine("\nDestroying the timer.");
  27. }
  28. }
  29.  
  30. class StatusChecker
  31. {
  32. int invokeCount, maxCount;
  33.  
  34. public StatusChecker(int count)
  35. {
  36. invokeCount = 0;
  37. maxCount = count;
  38. }
  39.  
  40. // This method is called by the timer delegate.
  41. public void CheckStatus(Object stateInfo)
  42. {
  43. AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
  44. Console.WriteLine("{0} Checking status {1,2}.",
  45. DateTime.Now.ToString("h:mm:ss.fff"),
  46. (++invokeCount).ToString());
  47.  
  48. if (invokeCount == maxCount)
  49. {
  50. // Reset the counter and signal Main.
  51. invokeCount = 0;
  52. autoEvent.Set();
  53. }
  54. }
  55. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.