System.Timers.Timer Life Cycle

which is the right approach to using System.Timers.Timer? I mean ... I create a timer, set the interval and method to call in the Expired event.

double ms = 1000;
var t = new System.Timers.Timer(ms);
t.AutoReset = false;
t.Elapsed += (sender, e) =>  { runTask(); }; 
t.Start();   

What's next? Should the call go to the timer? I suppose I can't, or the Elapsed event will never happen. Do I have to register a timer in a global variable to avoid losing references to it, and so could the GC manage the timer before calling Elapsed? And if so, how can I manage the timer after processing the Elapsed event (this way my task was completed)?

+3
source share
3 answers

: . , . , , .


, , GC, Disposed. , , , , GC ,
GC.KeepAlive(youtimer_Instance);

Timer Documentatio n .

:


        Normally, the timer is declared at the class level,
        so that it stays in scope as long as it is needed.
        If the timer is declared in a long-running method,  
        KeepAlive must be used to prevent the JIT compiler 
        from allowing aggressive garbage collection to occur 
        before the method ends. 
+1

(, - Windows), , , , , Timer.

System.Timers.Timer IDisposable, , , IDisposable, , , IDisposable, IDisposable Dispose(), .

System.Timers.Timer. System.Threading.Timer , , Dispose System.Timers.Timer

public void Dispose()
{
    this.timerBase.Dispose();
}

timerBase - System.Threading.Timer, Dispose , IDisposable.

+4

You should call t.Stop () on the Close / Unload of your form / page or anywhere you think is necessary. If you leave it running, it will use resources unnecessarily, and you can also get exceptions when you close the application.

0
source

Source: https://habr.com/ru/post/1791176/


All Articles