Lambdas within Extension methods: Possible memory leak?

Posted by Oliver on Stack Overflow See other posts from Stack Overflow or by Oliver
Published on 2010-04-06T10:10:25Z Indexed on 2010/04/06 10:13 UTC
Read the original article Hit count: 503

Filed under:
|
|

I just gave an answer to a quite simple question by using an extension method. But after writing it down i remembered that you can't unsubscribe a lambda from an event handler.

So far no big problem. But how does all this behave within an extension method??

Below is my code snipped again. So can anyone enlighten me, if this will lead to myriads of timers hanging around in memory if you call this extension method multiple times?

I would say no, cause the scope of the timer is limited within this function. So after leaving it no one else has a reference to this object. I'm just a little unsure, cause we're here within a static function in a static class.

public static class LabelExtensions
{
    public static Label BlinkText(this Label label, int duration)
    {
        Timer timer = new Timer();

        timer.Interval = duration;
        timer.Tick += (sender, e) =>
            {
                timer.Stop();
                label.Font = new Font(label.Font, label.Font.Style ^ FontStyle.Bold);
            };

        label.Font = new Font(label.Font, label.Font.Style | FontStyle.Bold);
        timer.Start();

        return label;
    }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about lambda