Is there an advantage to dynamically attaching/detaching event handlers?
Would manually detaching handlers help ensure that there isn\'t a reference remaining to a d
Most of the time the framework takes care of that for you.
Manually detaching an event can be important to prevent memory leaks: the object that connects to an event fired by another object, will not be garbage collected until the object that fires the event is garbage collected. In other words, an "event-raiser" has a strong reference to all the "event-listeners" connected to it.
I find that dynamically attaching/detaching event handlers is only of use where you have a long-lived object exposes events that are consumed by many short-lived objects. For most other cases the two objects are disposed around the same time and the CLR does a sufficient job of cleaning up on its own
It's not a question of using AddHandler versus Handles.
If you are concerned about the reference to your event handler interfering with garbage collection, you should use RemoveHandler, regardless of how the handler was attached. In the form or control's Dispose method, remove any handlers.
I have had situations in Windows Forms apps (.NET 1.1 days) where an event handler would be called on controls that had no other references to them (and which for all intents and purposes were dead and I would have thought been GC'ed) -- extremely hard to debug.
I would use RemoveHandler to get rid of handlers on controls that you are not going to reuse.
Declaring a field as WithEvents
will cause the compiler to automatically generate a property with that name. The getter returns the value of a backing field. The setter is a little more complicated. It first checks whether the backing field already has the correct value. If so, it exits. Otherwise, if the backing field is non-null, it issues "RemoveHandler" requests for all its events to the object identified by the backing field. Next, regardless of whether the backing field was non-null, it sets it equal to the requested value. Finally, if the new value is non-null, whether the old one was or not, the property issues "AddHandler" requests for all its events to the object identified by the new value.
Provided that one sets all of an object's WithEvents members to Nothing
before abandoning it, and avoids manipulating WithEvents members in multiple threads, the auto-generated event code will not leak.
I manually attach handlers when I manually create controls (for example, dynamically creating a TextBox for each database record). I manually detach handlers when they are handling things I'm not quite ready to handle yet (possibly because I'm using the wrong events? :) )