Search code examples
c#eventsgarbage-collectionanonymous-methods

What's keeping this timer in scope? The anonymous method?


Ok,

So I have a method which fires when someone clicks on our Icon in a silverlight application, seen below:

    private void Logo_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        e.Handled = true;
        ShowInfo(true);

        DispatcherTimer autoCloseTimer = new DispatcherTimer();
        autoCloseTimer.Interval = new TimeSpan(0, 0, 10);
        autoCloseTimer.Tick +=new EventHandler((timerSender,args) => 
            {
                autoCloseTimer.Stop();
                ShowInfo(false);
            });
        autoCloseTimer.Start();
    }

Whats meant to happen is that the method ShowInfo() opens up a box with the company info in and the dispatch timer auto closes it after said timespan. And this all works...

But what I'm not sure about is because the dispatch timer is a local var, after the Logo_MouseLeftButtonUp method finishes, what is there to keep the dispatch timer referenced and not availible for GC collection before the anonymous method is fired?

Is it the reference to the ShowInfo() method in the anonymous method?

Just feels like some thing I should understand deeper as I can imagine with using events etc it can be very easy to create a leak with something like this.

Hope this all makes sense!

Andy.


Solution

  • The DispatcherTimer registers itself with the Dispatcher by calling the internal Dispatcher.AddTimer method when you call Start.

    Since it also unregisters itself by calling Dispatcher.RemoveTimer when you call Stop, you won't leak memory.

    The Timer keeps the anonymous method alive in its Tick event, which also keeps the variables in the method alive through the closure.