Events and Garbage collection

  • Thread starter Sebastiaan Olijerhoek
  • Start date
S

Sebastiaan Olijerhoek

When an eventhandler is created to an object A that stays in use longer than
the object B that implements the eventhandler then the object B is not
release from memory before you remove the eventhandler manually (in a
Dispose method for instance). See code below.
Is this correct?
Are there any tips regards this?

Consider the following code:

class B
{
B()
{
System.Windows.Forms.Application.Idle += new
System.EventHandler(OnApplicationIdle);
}

void OnApplicationIdle(object sender, System.EventArgs e)
{
System.Diagnostics.Trace.Writeln("B.OnApplicationIdle");
}
}

class Form1 : System.Windows.Forms.Form
{
Form1()
{
// Creating an object
B temp = new B();

// Releasing object??
temp = null;
System.GC.Collect();
}

static void Main()
{
Application.Run(new Form1();
}
}
 
G

Guest

Right.

In this case, within the constructor for B, you give the Application a
reference to an eventhandler in B. This is just like any other object
reference.

So in the Form1 constructor, it doesn't matter that you set temp to null,
the Application still has a refence to the actual object in memory even
though your local reference is null.

As a consumer of B, within the main Form, this is confusing. I would change
B so that it doesn't add its own eventhandler to the Application's event.
Make that the responsibility of the application.

Thus you add the event handler in the Form code, and when you're done with
B, you remove the event handler.

Another option (though I don't recommend it) is to make B implement
IDisposable and in the Dispose method, you detach the event handler.

Phil
http://haacked.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top