2

Imagine that there is a method:

public static void Foo()
{
    Timer timer = null;
    timer = new Timer(
        callback: _ =>
        {
            if (satisfied)
            {
                timer.Change(1000, Timeout.Infinite);
                return;
            }

            timer.Dispose();
        },
        state: null,
        dueTime: Timeout.Infinite,
        period: Timeout.Infinite);

    timer.Change(0, Timeout.Infinite);
}

When method Foo() finishes, the only thing that references timer is callback. And the only thing that references callback is timer. Will that circular referencing safe timer from garbage collection?

Egor Okhterov
  • 478
  • 2
  • 9
  • 34
  • Pretty sure it won't prevent the GC from collecting them if the callback function ended. The GC will iterate from available object to available object. The timer isn't available outside, neither is callback. Could be wrong. Waiting for a guru for a detailed explanation. – nkoniishvt Dec 11 '14 at 21:16
  • Certain timer implementations save themselves, some don't, I never remember which do and which don't; check the documentation for that page. – Servy Dec 11 '14 at 21:18
  • Probable answer here: http://stackoverflow.com/a/18137151/4049478 . It seems that because the state is null it won't prevent the GC from collecting it. – nkoniishvt Dec 11 '14 at 21:23
  • 2
    Circular references (having no root) will not prevent GC to collect them. Thus, `timer` may be collected "prematurely" - and your callback might not fire. – CouchDeveloper Dec 12 '14 at 07:36

1 Answers1

0

From TFM:

As long as you are using a Timer, you must keep a reference to it. As with any managed object, a Timer is subject to garbage collection when there are no references to it. The fact that a Timer is still active does not prevent it from being collected.

Note that this is specific to System.Threading.Timer. Some other Timer classes wind up with an implicit reference from the framework, and so don't require you to explicitly keep a reference to prevent collection.

As always, it pays to read the documentation for any API you're using.

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136