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

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

问题描述

说我们有以下方法:

  private MyObject foo = new MyObject(); 

//以后在类

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

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



在完成调用后,是否有任何方法解除该lambda事件处理程序 MethodThatFiresAnEvent

解决方案

是的,将其保存到变量中并取消挂起。



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

是的,如果没有,你会泄漏内存因为你每次都会连接一个新的委托对象。你也会注意到这一点,因为每次调用这个方法时,它都会向控制台转储越来越多的行数(不只是越来越多的数字,而是一个调用MethodThatFiresAnEvent它会转储任意数量的项目,一次为每个连接匿名方法)。


Say we have the following method:

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();
}

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

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;

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天全站免登陆