开发者

Is an object with an event attached and no references to it eligable for garbage collection?

Quote from C# language specification 3.9:

'2. If the object, or any part of it, cannot be accessed by any possible continuation of execution, other than the running of destructors, the object is considered no longer in use, and it becomes eligible for destruction...

For instance would the DispatcherTimer be eligible for garbage collection before the Tick event fires?

    public void DispatchCallbackAfter(Action callback, TimeSpan period)
    {
        DispatcherTimer time开发者_如何学Pythonr = new DispatcherTimer(DispatcherPriority.Normal, AppSettings.MainWindow.Dispatcher);
        timer.Tick += new EventHandler(DispatchCallback);
        timer.Interval = period;
        timer.Tag = new object[] {timer, callback};
        timer.Start();
    }

    private void DispatchCallback(object sender, EventArgs args)
    {
        DispatcherTimer t = (DispatcherTimer)sender;
        t.Stop();
        ((Action)((object[])t.Tag)[1])();
    }

NOTE: There is self reference to the timer in timer.Tag but I imagine that would not make any difference?


While the DispatcherTimer is running, the Dispatcher has a reference to it, and it will not get GCed. Once the timer stops and there is no external reference to it, it can be collected. That is, if your only references to the timer and the callback are within the timer and the callback, and the timer is stopped, the timer can be collected.

You can tell that the dispatcher takes a reference to a running timer by looking in Reflector (or your favorite decompiler) and seeing that the timer calls _dispatcher.AddTimer(this); in its start function and _dispatcher.RemoveTimer(this); in its stop function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜