Why does a Timer keep my object alive?

2019-01-23 19:49发布

Preface: I know how to solve the problem. I want to know why it arises. Please read the question from top to bottom.

As we all (should) know, adding event handlers can cause memory leaks in C#. See Why and How to avoid Event Handler memory leaks?

On the other hand, objects often have similar or connected life cycles and deregistering event handlers is not necessary. Consider this example:

using System;

public class A
{
    private readonly B b;

    public A(B b)
    {
        this.b = b;
        b.BEvent += b_BEvent;
    }

    private void b_BEvent(object sender, EventArgs e)
    {
        // NoOp
    }

    public event EventHandler AEvent;
}

public class B
{
    private readonly A a;

    public B()
    {
        a = new A(this);
        a.AEvent += a_AEvent;
    }

    private void a_AEvent(object sender, EventArgs e)
    {
        // NoOp
    }

    public event EventHandler BEvent;
}

internal class Program
{
    private static void Main(string[] args)
    {
        B b = new B();

        WeakReference weakReference = new WeakReference(b);
        b = null;
        GC.Collect();
        GC.WaitForPendingFinalizers();

        bool stillAlive = weakReference.IsAlive; // == false
    }
}

A and B reference each other implicitly via events, yet the GC can delete them (because it's not using reference counting, but mark-and-sweep).

But now consider this similar example:

using System;
using System.Timers;

public class C
{
    private readonly Timer timer;

    public C()
    {
        timer = new Timer(1000);
        timer.Elapsed += timer_Elapsed;
        timer.Start(); // (*)
    }

    private void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        // NoOp
    }
}

internal class Program
{
    private static void Main(string[] args)
    {
        C c = new C();

        WeakReference weakReference = new WeakReference(c);
        c = null;
        GC.Collect();
        GC.WaitForPendingFinalizers();
        bool stillAlive = weakReference.IsAlive; // == true !
    }
}

Why can the GC not delete the C object? Why does the Timer keep the object alive? Is the timer kept alive by some "hidden" reference of the timer mechanics (e.g. a static reference)?

(*) NB: If the timer is only created, not started, the issue does not occur. If it's started and later stopped, but the event handler is not deregistered, the issue persists.

标签: c# events timer
6条回答
够拽才男人
2楼-- · 2019-01-23 19:59

I think this is related to the way that the Timer is implemented. When you call Timer.Start(), it sets Timer.Enabled = true. Look at the implementation of Timer.Enabled:

public bool Enabled
{
    [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
    get
    {
        return this.enabled;
    }
    set
    {
        if (base.DesignMode)
        {
            this.delayedEnable = value;
            this.enabled = value;
        }
        else if (this.initializing)
        {
            this.delayedEnable = value;
        }
        else if (this.enabled != value)
        {
            if (!value)
            {
                if (this.timer != null)
                {
                    this.cookie = null;
                    this.timer.Dispose();
                    this.timer = null;
                }
                this.enabled = value;
            }
            else
            {
                this.enabled = value;
                if (this.timer == null)
                {
                    if (this.disposed)
                    {
                        throw new ObjectDisposedException(base.GetType().Name);
                    }
                    int dueTime = (int) Math.Ceiling(this.interval);
                    this.cookie = new object();
                    this.timer = new Timer(this.callback, this.cookie, dueTime, this.autoReset ? dueTime : 0xffffffff);
                }
                else
                {
                    this.UpdateTimer();
                }
            }
        }
    }
}

It looks like a new timer is created, with a cookie object passed to it (very odd!). Following that call path leads to some other complex code involving creating a TimerHolder and a TimerQueueTimer. I expect at some point a reference held outside the Timer itself is created, until such time as you call Timer.Stop() or Timer.Enabled = false.

This isn't a definitive answer, since none of the code I posted creates such a reference; but it's complicated enough down in the guts to lead me to suspect that something like that is happening.

If you have Reflector (or similar) have a look and you'll see what I mean. :)

查看更多
唯我独甜
3楼-- · 2019-01-23 20:01

Because Timer is still active. (Event handler is not removed for Timer.Elapsed).

If you want to properly dispose, Implement IDisposable interface, remove the event handler in the Dispose method, and use the using block or call the Dispose manually. The issue will not occur.

Example

 public class C : IDisposable  
 {
    ...

    void Dispose()
    {
      timer.Elapsed -= timer_elapsed;
    }
 }

And then

 C c = new C();

 WeakReference weakReference = new WeakReference(c);
 c.Dispose();
 c = null;
查看更多
smile是对你的礼貌
4楼-- · 2019-01-23 20:16

The timer logic relies on an OS functionality. It is actually the OS that fires the event. OS in turn uses CPU interrupts to implement that.

The OS API, aka Win32, does not hold references to any objects of any kind. It holds memory addresses of functions which it has to call when a timer event happens. .NET GC has no way to track such "references". As a result a timer object could be collected without unsubscribing from the low-level event. It is a problem because OS would try to call it anyway and would crash with some weird memory access exception. That's why .NET Framework holds all such timer objects in the statically referenced object and removes them from that collection only when you unsubscribe.

If you look at the root of your object using SOS.dll you will get the next picture:

!GCRoot 022d23fc
HandleTable:
    001813fc (pinned handle)
    -> 032d1010 System.Object[]
    -> 022d2528 System.Threading.TimerQueue
    -> 022d249c System.Threading.TimerQueueTimer
    -> 022d2440 System.Threading.TimerCallback
    -> 022d2408 System.Timers.Timer
    -> 022d2460 System.Timers.ElapsedEventHandler
    -> 022d23fc TimerTest.C

Then if you look at the System.Threading.TimerQueue class in something like dotPeek, you will see that it is implemented as a singleton and it holds a collection of timers.

That's how it works. Unfortunately the MSDN documentation is not crystal clear about it. They just assumed that if it implements IDisposable then you should dispose it no question asked.

查看更多
祖国的老花朵
5楼-- · 2019-01-23 20:18

Is the timer kept alive by some "hidden" reference of the timer mechanics (e.g. a static reference)?

Yes. It is built in the CLR, you can see a trace of it when you use the Reference Source or a decompiler, the private "cookie" field in the Timer class. It is passed as the second argument to the System.Threading.Timer constructor that actually implements the timer, the "state" object.

The CLR keeps a list of enabled system timers and adds a reference to the state object to ensure it doesn't get garbage collected. Which in turn ensures that the Timer object doesn't get garbage collected as long as it is in the list.

So getting a System.Timers.Timer garbage collected requires that you call its Stop() method or set its Enabled property to false, same thing. Which cause the CLR to remove the system timer from the list of active timers. Which also removes the reference to the state object. Which then makes the timer object eligible for collection.

Clearly this is desirable behavior, you do not typically want to have a timer just disappear and stop ticking while it is active. Which will happen when you use a System.Threading.Timer, it stops calling its callback if you don't keep a reference to it, either explicitly or by using the state object.

查看更多
女痞
6楼-- · 2019-01-23 20:19

I think the problem arises from this line;

c = null;

In general, most developers think that making an object equal to null results in object to be deleted by garbage collector. But this is not the case; in fact only a reference to a memory location (where c object is created) is deleted; if there are any other references to the related memory location, object will not be marked for deletion. In this case, since Timer is referencing the related memory location, object will not be deleted by garbage collector.

查看更多
Anthone
7楼-- · 2019-01-23 20:19

Let's first talk about Threading.Timer. Internally, the timer will construct a TimerQueueTimer object using callback and state passed to Timer ctor (say new Threading.Timer(callback, state, xxx, xxx). The TimerQueueTimer will be added to a static list.

If callback method and state have no "this" info (say using static method for callback and null for state), then the Timer object can be GCed when no reference. On the other hand, if a member method is used for callback, the delegate containing "this" will be stored in the static list mentioned above. So Timer object cannot be GCed since the "C" (in your example) object is still referenced.

Now let's back to System.Timers.Timer which internally wraps Threading.Timer. Note that when the former constructs the latter, a System.Timers.Timer member method is used, so System.Timers.Timer object cannot be GCed.

查看更多
登录 后发表回答