System.Timers.Timer lifecycle

前端 未结 3 1516
深忆病人
深忆病人 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:27

    If you are using Timers during a long running process (e.g. a web application or a windows service), if you don't want to get a memory leak, you need to ensure that you un-subscribe from the Timer's elapsed event handler if you want the garbage collector to be able to reclaim the memory allocated for the Timer object.

    System.Timers.Timer implements IDisposable and the guidelines here are that if you have a class that implements IDisposable, any class that has a dependency on an object implementing IDisposable should implement IDisposable itself and call the objects Dispose() method when it itself is called.

    A perfect example of this is indeed with System.Timers.Timer. This uses System.Threading.Timer underneath the covers and if you look in reflector you can see the following for the Dispose method on System.Timers.Timer

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

    Here, timerBase is simply an instance of System.Threading.Timer and therefore the Dispose call cascades down to all dependencies of the class that implement IDisposable.

提交回复
热议问题