Can using lambdas as event handlers cause a memory leak?
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).
You wont just leak memory, you will also get your lambda called multiple times. Each call of 'PotentialMemoryLeaker' will add another copy of the lambda to the event list, and every copy will be called when 'AnEvent' is fired.
那么你可以扩展在这里做的事情,使代表更安全地使用(没有内存泄漏)
链接地址: http://www.djcxy.com/p/51468.html上一篇: C#事件和线程安全