Can using lambdas as event handlers cause a memory leak?

扶醉桌前 提交于 2019-11-28 06:52:44

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.

Well you can extend what has been done here to make delegates safer to use (no memory leaks)

Your example just compiles to a compiler-named private inner class (with field firedCount and a compiler-named method). Each call to PotentialMemoryLeaker creates a new instance of the closure class to which where foo keeps a reference by way of a delegate to the single method.

If you don't reference the whole object that owns PotentialMemoryLeaker, then that will all be garbage collected. Otherwise, you can either set foo to null or empty foo's event handler list by writing this:

foreach (var handler in AnEvent.GetInvocationList()) AnEvent -= handler;

Of course, you'd need access to the MyObject class's private members.

Nick Berardi

Yes in the same way that normal event handlers can cause leaks. Because the lambda is actually changed to:

someobject.SomeEvent += () => ...;
someobject.SomeEvent += delegate () {
    ...
};

// unhook
Action del = () => ...;
someobject.SomeEvent += del;
someobject.SomeEvent -= del;

So basically it is just short hand for what we have been using in 2.0 all these years.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!