Can using lambdas as event handlers cause a memory leak?

前端 未结 5 878
被撕碎了的回忆
被撕碎了的回忆 2020-12-08 21:43

Say we have the following method:

private MyObject foo = new MyObject();

// and later in the class

public void PotentialMemoryLeaker(){
  int firedCount =          


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-08 22:21

    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).

提交回复
热议问题