StrataFrame Forum

Garbage collection and manual intervention

http://forum.strataframe.net/Topic9667.aspx

By Peter Denton - 6/19/2007

G'day

I was just reading through the forum looking for some information on broken rules (found it!) when I came across the topic

http://forum.strataframe.net/Topic4577-6-1.aspx?

In this Trent states

... the number one killer of many .NET developers is not cleaning up after the code and expecting the garbage collector to do the work.  The other thing, that goes hand in hand here, are event handlers.  If you ever gain a handler reference to any object, not just a BO, it will stay there until you explicitly remove the handler.  ... you will definitely want to Dispose your manually created objects when you are through with them...whether it be a BO or some other type of object.

Previously I hadn't given much thought to garbage collection and disposing of objects, but I will certainly try to now.

I didn't quite follow what was said next about event handlers.

My understanding is that if in a form I have something like:

Private Sub btnRefresh_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRefresh.Click

Me.PopulateGrid1()

End Sub

This will be garbage collected  when the form (i.e. the class handling the event) exits.

Is this correct?

Could someone provide an example of an event handler that wouldn't be disposed, say when a form exits, and how and where it should be disposed if I did want to get rid of it when the form exits?

Peter

By StrataFrame Team - 6/20/2007

In VB, if you use the Handles keyword, you don't have to worry about cleaning it up.  In fact, there's really not a keyword to remove an implicitly created handler like that...

However, if you ever use the "AddHandler obj.Event, AddressOf MethodHandler" to add an event that you didn't define WithEvents, you should remember to call the "RemoveHandler obj.Event, AddressOf MethodHandler" on it.

By Peter Denton - 6/20/2007

Thanks Ben

 I think I've got it now.

Peter

By StrataFrame Team - 6/21/2007

Excellent Smile