Search code examples
c#garbage-collectionanonymous-methods

When are method variables, accessible in an anonymous method, garbage collected?


For instance is it necessary to add a Timer instance to a list as I am doing here to prevent the Timer being garbage collected? Tyically if the callback was not anonymous the aswer is yes, but since it is anonymous i imagine the variables in the method block which are accessible in the anonymous method block will only be garbage collected when the anonymous method completes? In which case no need to save ref as I am doing..:

private static List<Timer> timers = new List<Timer>();

public static void RunCallbackAfter(Action callback, int secondsToWait)
{
        Timer t = null;
        t = new Timer(new TimerCallback(delegate(object state)
            {
                SomeThread.BeginInvoke(callback);
                timers.Remove(t);
            }), null, secondsToWait*1000, Timeout.Infinite);
        timers.Add(t);
}

Solution

  • The objects referred to by the captured variables in the anonymous method will not be eligible for garbage collection until the delegate created by the anonymous method is eligible for garbage collection.

    However, if it's only the Timer which has a reference to the delegate, and nothing else has a reference to the timer, then I suspect both would be eligible for garbage collection, assuming this is indeed the kind of timer which you need to keep a reference to. (I seem to remember that some timers do require this and some don't. I can't remember which is which.)

    Also, if you removed the timers.Remove(t) call from within the anonymous method then it wouldn't be capturing t in the first place. It's only captured variables which have prolonged lifetimes... not every variable in the method which contains the anonymous method.