Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is unwired event a memory leak?

Tags:

c#

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?

like image 298
Prince Ashitaka Avatar asked Sep 07 '10 18:09

Prince Ashitaka


2 Answers

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:

  1. Is there something that needs to be done with events that do not have any delegates attached to them?
  2. Can an event prevent objects from getting cleaned up by the garbage collector?

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.

like image 98
Adam Robinson Avatar answered Oct 04 '22 13:10

Adam Robinson


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.

like image 45
kemiller2002 Avatar answered Oct 04 '22 13:10

kemiller2002