Why C# compiler generates single class to capture variables of several lambdas?
<p>Assume we have such code:</p>

<pre><code>public class Observer
{
    public event EventHandler X = delegate { };
}

public class Receiver
{
    public void Method(object o) {}
}

public class Program
{
    public static void DoSomething(object a, object b, Observer observer, Receiver r)
    {
        var rCopy = r;
        EventHandler action1 = (s, e) =&gt; rCopy.Method(a);
        EventHandler action2 = (s, e) =&gt; r.Method(b);
        observer.X += action1;
        observer.X += action2;
    }

    public static void Main(string[] args)
    {
        var observer = new Observer();
        var receiver = new Receiver();
        DoSomething(new object(), new object(), observer, receiver);
    }
}
</code></pre>

<p>Here <code>action1</code> and <code>action2</code> have completely separated set of captured variables - <code>rCopy</code> was created especially for this. Still, compiler generates just one class to capture everything (checked generated IL). I suppose it is done for optimization reasons, but it allows very hard-to-spot memory leak bugs: if <code>a</code> and <code>b</code> captured in single class, GC is unable to collect both at least so long as <em>any</em> of lambdas are referenced.</p>

<p>Is there a way to convince compiler to produce two different capture classes? Or any reason why it cannot be done?</p>

<p>P.S. Somewhat more detailed, in my blog: <a href="http://sparethought.wordpress.com/2012/08/17/implicit-closures-in-c-lambdas/">here</a> and <a href="http://sparethought.wordpress.com/2012/08/17/implicit-closures-in-c-lambdas-part-2/">here</a>.</p>
