使用 lambdas 作为事件处理程序会导致内存泄漏吗? [英] Can using lambdas as event handlers cause a memory leak?

查看:39
本文介绍了使用 lambdas 作为事件处理程序会导致内存泄漏吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有以下方法:

private MyObject foo = new MyObject();

// and later in the class

public void PotentialMemoryLeaker(){
  int firedCount = 0;
  foo.AnEvent += (o,e) => { firedCount++;Console.Write(firedCount);};
  foo.MethodThatFiresAnEvent();
}

如果有这个方法的类被实例化,并且PotentialMemoryLeaker方法被多次调用,我们是否会泄漏内存?

If the class with this method is instantiated and the PotentialMemoryLeaker method is called multiple times, do we leak memory?

在我们调用完 MethodThatFiresAnEvent 之后,有什么方法可以解除该 lambda 事件处理程序的挂接吗?

Is there any way to unhook that lambda event handler after we're done calling MethodThatFiresAnEvent?

推荐答案

是的,将其保存到一个变量中并取消挂钩.

Yes, save it to a variable and unhook it.

DelegateType evt = (o, e) => { firedCount++; Console.Write(firedCount); };
foo.AnEvent += evt;
foo.MethodThatFiresAnEvent();
foo.AnEvent -= evt;

是的,如果你不这样做,你会泄漏内存,因为你每次都会连接一个新的委托对象.您还会注意到这一点,因为每次调用此方法时,它都会向控制台转储越来越多的行(不仅仅是增加的行数,而且对于 MethodThatFiresAnEvent 的一次调用,它会转储任意数量的项目,一次用于每个连接匿名方法).

And yes, if you don't, you'll leak memory, as you'll hook up a new delegate object each time. You'll also notice this because each time you call this method, it'll dump to the console an increasing number of lines (not just an increasing number, but for one call to MethodThatFiresAnEvent it'll dump any number of items, once for each hooked up anonymous method).

这篇关于使用 lambdas 作为事件处理程序会导致内存泄漏吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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