Assume we have such 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) => rCopy.Method(a);
EventHandler action2 = (s, e) => 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);
}
}
Here action1
and action2
have completely separated set of captured variables - rCopy
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 a
and b
captured in single class, GC is unable to collect both at least so long as any of lambdas are referenced.
Is there a way to convince compiler to produce two different capture classes? Or any reason why it cannot be done?
P.S. Somewhat more detailed, in my blog: here and here.
question from:
https://stackoverflow.com/questions/12009309/why-c-sharp-compiler-generates-single-class-to-capture-variables-of-several-lamb 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…