OT: Remove static/shared event handler in finalize?

OT: Remove static/shared event handler in finalize?

Old forum URL: forums.lhotka.net/forums/t/3713.aspx


Henrik posted on Monday, October 15, 2007

Hi all

In each of my EditableRoots I have a shared/static event named ObjectChanged, which is raised when an object is added, updated or deleted.

My RO lists subscribes to these events to add, update or remove the respective RO item in question.

Now, I subscribe to the events in the RO list contructor with:

Private Sub New()
   AddHandler [BusinessObject].ObjectChanged, AddressOf ObjectChangedHandler
End Sub

My question is: must I remove the handler to the shared/static event again and if so, where should I remove the handler?

I have thought about removing it in the Finalize method, but have read everywhere that Finalize should only be overriden if you have that 1 in a fantazillion odd case, which I don't think the above pattern is one off.

Thanks in advance

/Henrik

 

Henrik replied on Monday, October 15, 2007

After some longhaired debugging I found that the shared/static event handlers needs to be removed, otherwise the handler (which delegate has a reference to the list) keeps the list in memory indefinitely.

However removing the handler in the finalizer won't work since the GC is responsible for calling this and does it at arbitrary times (even after the app has ended).

So I have implemented IDisposable on the RO lists in which the shared/static event handlers are removed.

The downside to this is that the clients of the RO lists must dispose the lists with a specific call to Dispose, which is easy to forget.

I recall reading a blog entry by Rocky a few days ago where one of the comments warned against something like this, but I cannot seem to find the blog entry again for an alternate solution. Rocky can you help me with this?

Copyright (c) Marimer LLC