title: What kind of memory leaks do lambda event handlers cause?
body: <p>Event handlers can easily lead to memory leaks, because the event's invocation list holds a reference to the event handling instance, so that the event handling instance cannot be garbage collected, if the event source is still alive.</p>
  
  <p>But consider the following code:</p>
  
  <pre><code>public class SomeClass
  {
      public event EventHandler SomeEvent;
  }
  public class MyClass
  {
      public MyClass(SomeClass source)
      {
          //VERSION 1
          source.SomeEvent += OnSomeEvent;
  
          //VERSION 2
          void localHandler(object s, EventArgs args) { Console.WriteLine("some action with(out) any references"); }
          source.SomeEvent += localHandler;
  
          //VERSION 3
          var x = new object();
          source.SomeEvent += (s, e) =&gt; { Console.WriteLine("some event fired, using closure x:" + x.GetHashCode()); };
  
          //VERSION 4
          source.SomeEvent += (s, e) =&gt; { Console.WriteLine("some action without any references"); };
      }
  
      private void OnSomeEvent(object sender, EventArgs e) 
      {
          //...
      }
  }
  </code></pre>
  
  <p>My assumptions/questions why the different event handling versions may cause a memory leak:</p>
  
  <ul>
  <li>Version 1: Because the invocation target clearly references the instance of <code>MyClass</code>.</li>
  <li>Version 2: Because the reference to <code>localHandler</code> implies a reference to the instance of <code>MyClass</code> - except, maybe, if the code inside <code>localHandler</code> has no references to the instance of <code>MyClass</code>?</li>
  <li>Version 3: Because the lambda contains a closure, which itself is a reference to the instance of <code>MyClass</code> - or is it? </li>
  <li>Version 4: Because the lambda does not reference the instance of <code>MyClass</code>, this may not cause a leak?</li>
  </ul>
  
  <p>And, follow-up questions to versions 3 and 4: </p>
  
  <ul>
  <li>Where is the "magic helper object" that .Net creates for the lambda/closure stored and does it (always) include a reference that would keep the instance of <code>MyClass</code> alive?</li>
  <li>If lambda event handlers can leak, they should only be used in scenarios where this is not a problem (e.g. <code>MyClass</code> instances outlive <code>SomeClass</code> instances), because they cannot be removed using <code>-=</code>?</li>
  </ul>
  
  <p><strong>EDIT:</strong> This post (with the original title "When can event handlers cause memory leaks?") was suggested as a duplicate, of <a href="https://stackoverflow.com/questions/4526829/why-and-how-to-avoid-event-handler-memory-leaks">Why and How to avoid Event Handler memory leaks?</a>, but I disagree, because the question was directed at lambda event handlers specifically. I rephrased the question/title to make this more clear.</p>