【问题标题】:Does hooking up an event that is self referencing cause a memory leak?连接自引用的事件会导致内存泄漏吗?
【发布时间】:2019-12-10 11:42:44
【问题描述】:

所以我有一个简单的类:

public class GridButton : Button
{
    public event EventHandler OnClick;

    public GridButton()
    {
        this.Clicked += GridButton_Clicked;     
    }

    private void GridButton_Clicked(object sender, EventArgs e)
    {
        HandleTap();
    }

现在,由于这是一个视图控件,我不负责处理此对象的时间。

上面的代码是内存泄漏还是GarbageCollector 足够聪明,可以确定事件处理程序是自引用的,因此不会导致泄漏。

如果这是内存泄漏,正确的解决方案是什么?

我应该使用更多的WeakRefence 吗,就像这里的 oulined 一样?

http://paulstovell.com/blog/weakevents

【问题讨论】:

    标签: c# memory-leaks event-handling eventhandler


    【解决方案1】:

    .NET 垃圾收集器将查找并删除循环 (this -> OnClick -> this.GridButton_Clicked)。

    .NET 中的“内存泄漏”往往发生在你说一个永远不会被释放的集合(例如列表、映射、事件等)(例如全局/静态变量,或者在开始时)在程序期间不会超出范围的堆栈),然后随着时间的推移不断向其中添加更多项,但永远不要删除它们。

    例如:

    public GridButton()
    {
        Globals.OnRefreshClicked += Refresh;     
    }
    private void Refresh()
    {
       ...update text, state, whatever...
    }
    

    “Globals”是指任何长期存在的东西。现在,即使您从 GUI 中移除此按钮,除非您也移除该事件,否则 Globals.OnRefreshClicked -> this.Refresh 引用将使您的对象保持活动状态,至少与 Globals 一样长,这可能会持续到程序终止。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-23
      • 2021-09-25
      • 2014-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多