Dynamic Event Handling
Here's a random question.
I have an object called Monkey, and an object called Banana. The Banana exposed an event called Ripens which the Monkey object subscribes to. When the Ripens event is triggered, the Monkey calls its Consume() function, which in turn destroys the Banana Object.
Example:
//And yes, I know this isnt real C# code. Just trying to get my point across and
//not necessarily be syntatically correct with this exmaple.
public class Banana
{
public event Ripens;
}
public class Monkey
{
public Monkey()
{
List<Banana> tree = new List<Banana>();
for (int i = 0; i < 8; i ++)
{
tree.Add(new Banana());
tree[i].Ripens += this.Consume;
}
}
public void Consume(Banana b)
{
tree.Remove(b);
b.Destroy();
}
}
So my question then is: Does the Monkey bleed memory for each banana that is destroyed without first unsubscribing from its events. Or do the event handlers i开发者_开发问答n Monkey get destroyed along with the banana?
When monkey subscribes to banana it's the banana that now has a reference to the monkey and monkey does not have one to banana. In your example when bananas risen they are now subject for garbage collection. So no - monkey doesn't leak memory.
"Memory leaks" from events actually occur in the other direction. If the monkey goes out of scope, the banana event still has a reference to the event delegate on the monkey, so the Monkey will not get Garbage Collected.
To address your "each" question, yes - the event handlers are per-object. So multiple subscribers going out of scope would still have references to them via the event publisher, causing them to not be garbage collected.
精彩评论