0

As stated in the title, When is a System.Timers Timer disposed?

In a scenario where I would run a console application and simply use the following code

var timer = new Timer( interval );
timer.Enabled = true;
timer.Elapsed += MainTimer_Elapsed;

Will the timer be disposed at some point or will it be "alive" forever? Note: With "forever" I mean until the application is closed.

VisualBean
  • 4,908
  • 2
  • 28
  • 57
  • You can visit this link for details http://stackoverflow.com/questions/4955821/system-timers-timer-lifecycle – J.SMTBCJ15 Mar 03 '17 at 10:45
  • It will be alive "forever" because you don't unsubscribe the event handler or dispose the timer. It implements `IDisposable` for one reason: it uses unmanaged resources, in this case a Win32 timer which events prevents the timer from being garbage collected. – Tim Schmelter Mar 03 '17 at 10:50
  • 2
    @TimSchmelter - unlike threads, timers don't keep themselves rooted. So, at some unknown future point in time, the timer will be GCed and at that point it will probably dispose itself. – Damien_The_Unbeliever Mar 03 '17 at 10:52
  • 1
    @Damien_The_Unbeliever: haven't tested it but [this question](http://stackoverflow.com/questions/4962172/why-does-a-system-timers-timer-survive-gc-but-not-system-threading-timer) suggests that `System.Timers.Timer` might not be garbage collected(depends on the constructor used). – Tim Schmelter Mar 03 '17 at 10:59
  • @Damien_The_Unbeliever Tim is right, System.Timers.Timer will not be collected if you don't unsubsribe or dispose. – Evk Mar 03 '17 at 11:12

0 Answers0