System.Timers.Timer lifecycle

前端 未结 3 1515
深忆病人
深忆病人 2021-01-20 02:35

which is the right approach to use a System.Timers.Timer? I mean... I create the timer, set the interval and the method to be called on the Elapsed event.

do         


        
3条回答
  •  礼貌的吻别
    2021-01-20 03:22

    A short answer is you don't need to do anything. It will be collected by the Garbage Collector when function goes out of scope. If you want it available then declare it in class instead.


    Usually when you declare a timer out in class level it is collected by GC when the Class is Disposed. However when you have your timer declare in a Function then the Timer still runs but if you are executing a very long process then GC can Aggressively Dispose it so you will need to use

    GC.KeepAlive(youtimer_Instance);
    

    Have a look at the end of the Timer's Documentation for reference to this scenario.

    The Comments in the sample code says:

    
            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. 
    

提交回复
热议问题