使用实时事件处理程序对未引用对象进行垃圾收集 [英] Garbage collection of unreferenced object with live event handler

查看:36
本文介绍了使用实时事件处理程序对未引用对象进行垃圾收集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下程序中...

using System;

class Program
{
    static Parent parent;

    static void Main( string[] args )
    {
        parent = new Parent();
        // The program hereafter runs for a long time and occasionally
        // causes parent.SomeEvent to be raised.
    }
}

class Parent
{
    public event EventHandler SomeEvent;

    public Parent()
    {
        new Handler( this );
    }
}

class Handler
{
    public Handler( Parent parent )
    {
        parent.SomeEvent += parent_SomeEvent;
    }

    void parent_SomeEvent( object sender, EventArgs e )
    {
        // Does something important here.
    }
}

请注意,尽管实例化的 Handler 对象已预订 SomeEvent ,但未引用该对象.是否有可能在程序运行一段时间后,垃圾收集器可能决定消除 Handler 实例,因此,只要 parent.SomeEvent 引发了?

Notice that the instantiated Handler object is not referenced, although it has subscribed to SomeEvent. Is it possible that, after the program is running for a while, the garbage collector may decide to eliminate the Handler instance and its parent_SomeEvent handler will therefore no longer be called whenever parent.SomeEvent is raised?

我需要对正在编写的应用程序进行说明.如上所示,有许多类似 Handler 的对象被实例化,而没有被引用. Handler 的主要目的是订阅 SomeEvent .没有有用的方法来调用对 Handler 实例的引用,因此我可以不引用它.调试时我没有遇到任何问题.但是,现在我担心的是,当应用程序长时间运行并且垃圾收集器更加活跃时,部署后可能会出现问题.

I need this clarification for an app I am writing. There are many Handler-like objects that are instantiated as shown above, without being referenced. The central purpose of Handler is to subscribe to SomeEvent. There are no useful methods to call on a reference to the Handler instance, so I would be fine not referencing it otherwise. I haven't encountered any problems while debugging. But now I am concerned that issues may arise after deployment when the app is running for long periods of time and the garbage collector is more active.

推荐答案

在运行程序时, Parent 类包含对您所使用的 EventHandler 委托实例的引用.在 Handler 构造函数中重新创建,并且委托实例保存对 Handler 实例的引用.因此,只要有对 Parent 实例的引用,就不会对 Handler 实例进行垃圾回收.

When you run your program, the Parent class holds a reference to the EventHandler delegate instance you're creating in the Handler constructor, and the delegate instance holds a reference to the Handler instance. So the Handler instance will not be garbage collected as long as there is a reference to the Parent instance.

这篇关于使用实时事件处理程序对未引用对象进行垃圾收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆