staafl

timer not GC-ed

Jan 10th, 2014
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.84 KB | None | 0 0
  1. // why isn't the timer being disposed? see example session after code
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Timers;
  6. class Program
  7. {
  8. static void Main()
  9. {
  10. StartTimer();
  11. Console.WriteLine("Timer started");
  12. while(true)
  13. {
  14. Console.ReadLine();
  15. GC.Collect();
  16. GC.WaitForPendingFinalizers();
  17. GC.Collect();
  18. Console.WriteLine("GC.Collect complete");
  19. }
  20. }
  21. static void StartTimer()
  22. {
  23. var timer = new Timer();
  24. timer.Interval = 1000;
  25. timer.Elapsed += (_1, _2) => Console.WriteLine("TICK");
  26. timer.Start();
  27. }
  28. }
  29.  
  30. /*
  31. \> timer.exe
  32. Timer started
  33. TICK
  34. TICK
  35. TICK
  36.  
  37. GC.Collect complete
  38. TICK
  39. TICK
  40. TICK
  41.  
  42. GC.Collect complete
  43. TICK
  44. TICK
  45. TICK
  46.  
  47. GC.Collect complete
  48. TICK
  49. TICK
  50. TICK
  51. TICK
  52. TICK
  53. TICK
  54. TICK
  55. TICK
  56. <Ctrl+C>*/
Advertisement
Add Comment
Please, Sign In to add comment