No matter what you ask, the technical answer to your question is no. Technically, if you don't find an error in the CLR, there are no true “memory leaks” with managed objects (which is most of what makes them a good thing). To answer what I think you are really asking, it looks like you are asking one of two things:
- Is there something that needs to be done with events in which there are no delegates attached to them?
- Can an event prevent garbage collection from clearing objects?
The answer to the first question is simply no. Move on, nothing is visible here.
The answer to the second is discussed in detail here in SO and other areas of the network. The short version is that a related event handler means that the GC will treat the target instance as "reachable" by the event instance. This can lead to the fact that objects remain in memory longer than expected, since this availability is somewhat transparent to the user (developer) due to the way delegates are created.
In other words, let's say I have two objects: Producer and Consumer. The producer fires an event that the 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 Consumer instance where AttachTo is called will remain available to the GC as long as the Producer instance to which it is attached does not have the right to collect, because the delegate for the implementation of the OmgIDidSomething event has a reference to the Consumer instance that matches.
Adam robinson
source share