detaching events

  • Thread starter Thread starter Sean Malloy
  • Start date Start date
S

Sean Malloy

Hi,

I'm new to windows forms development.

I'm just wondering what the best practise is to deatching events.

I have an external object which is passed into a dialog form. The dialog
wires up a couple of EventHandlers. to listen for events on the object.

Now I have a suspicion that even when I dispose of the form, it is still
hanging around and can't be garbage collected, because a delegate is still
pointing to it because it is still bound to events on another object.

Is this the case?

I've looked through a number of example applications, and I can't find any
examples of people actualy detaching their events once they're finished with
them.

What does everyone else do? Should I detach them, and if so, when?
 
Hi Sean,

I'm quite new to C# also so I might be thinking in different terms to you,
but if you use: i.MyEvent -= new MyDelegate(f);
(after using i.MyEvent += new MyDelegate(f);)
it removes the event form the delegate's control. It's the -= that does it.

hope that helps,

Alan
 
I'm quite new to C# also so I might be thinking in different terms to you,
but if you use: i.MyEvent -= new MyDelegate(f);
(after using i.MyEvent += new MyDelegate(f);)
it removes the event form the delegate's control. It's the -= that does it.

hope that helps,

Alan


Hi Alan,

thanks for the pointer, but I'm already aware of the syntax to remove an
event handler.

My question was aimed more at "Should I always explicitly remove my event
handlers" in situations where a custom child form is binding to parent forms
events.

My instinct tells me there are going to be left over events bound, and the
garbage collector is never going to reclaim that memory because the closed
forms still have references maintained due to the bound events. In effect a
memory leak.
 
Hi Sean,

In my reading about the GC and it's functions, I believe it is not
necessary to deconstruct your delegates when disposing the child form
object. The GC should clean up any pointers used by the object in
memory. This assumption can also be supported by the fact that the IDE
doesn't create a deconstructor method for form class objects, but rather
just uses the Displose() method to allow the GC to do its thing.

Coming from a background starting with VB4, I completely understand your
concern with memory leaks in any case. You can prove this theory by
creating a test app with your custom child form creation method and
calling the GC.Collect() method. You can then test the memory in the
test app using GC.GetTotalMemory(false) before and after the collection
method to ensure the memory is being released as advertised.

Hope this helps,

- Glen
 
Back
Top