class A
{
public event EventHandler AEvent;
}
class B
{
private A _foo;
private int _bar;
public void AttachToAEvent()
{
_foo.AEvent += delegate()
{
...
UseBar(_bar);
...
}
}
}
Since delegate captures variable this._bar, does it implicitly hold to the instance of B? Will instance of B be referenced through the event handler and captured variable by an instance of A?
Would it be different if _bar was a local variable of the AttachToAEvent method?
Since in my case an instance of A lives far longer and is far smaller than an instance of B, I’m worried to cause a “memory leak” by doing this.
This is easiest understood by looking at the code generated by the compiler, which is similar to:
As can be plainly seen, the delegate created is an instance-delegate (targets an instance method on an object) and must therefore hold a reference to this object instance.
Actually, the anonymous method captures just
this(notthis._bar). As can be seen from the generated code, the constructed delegate will indeed hold a reference to theBinstance. It has to; how else could the field be read on demand whenever the delegate is executed? Remember that variables are captured, not values.Yes, you have every reason to be. As long as the
Ainstance is reachable, theBevent-subscriber will still be reachable. If you don’t want to go fancy with weak-events, you need to rewrite this so the handler is unregistered when it is no longer required.Yes, it would, as the captured variable would then become the
barlocal rather thanthis.But assuming that
UseBaris an instance-method, your “problem” (if you want tot think of it that way) has just gotten worse. The compiler now needs to generate an event-listener that “remembers” both the local and the containingBobject instance.This is accomplished by creating a closure object and making it (really an instance method of it) the target of the delegate.