If yes, is there a way to unwire it globally for all wired events
Edit: Say for example. I have objects, each tagged with an event like orm.NatureChanged += Nature_Changed;
I tag these events when i create each orm instance. If I didn't unwire by means like orm.NatureChanged -= Nature_Changed;
will it cause memory leak?
Regardless of what you're asking, the technical answer to your question is "no". Technically, unless you discover a bug in the CLR, there are no true "memory leaks" with managed objects (that's a big part of what makes them a Good Thing). To answer what I think you're actually asking, though, it sounds like you're asking one of two things:
The answer to the first question is simply "no". Move along, nothing to see here.
The answer to the second has been discussed at length here on SO and other areas of the web. The short version is that an attached event handler means that the GC will consider the target instance as "reachable" by the event-firing instance. This can cause objects to remain in memory longer than expected, since this reachability is somewhat transparent to the user (developer) because of the way delegates are constructed.
In other words, say I have two objects: Producer and Consumer. Producer fires an event that Consumer...consumes.
public class Producer
{
public event EventHandler OmgIDidSomething;
}
public class Consumer
{
public void AttachTo(Producer producer)
{
producer.OmgIDidSomething += new EventHandler(producer_OmgIDidSomething);
}
private void producer_OmgIDidSomething(object sender, EventArgs e)
{
// ...
}
}
In this example, any instance of Consumer
where AttachTo
is called will remain reachable as far as the GC is concerned until the instance of Producer
that it attached to is eligible for collection, because the delegate behind the implementation of the OmgIDidSomething
event has a reference to the instance of Consumer
that it corresponds to.
No, because when you unwire an event, the delegate (it's an object) which was wired to the event is no longer rooted, and will be collected when the GC sees fit to do so. This is assuming of course the event delegate isn't attached to multiple handlers, in which case it won't be collected until it is unwired from all events.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With