From a memory point of view (remove an added handler after utilization, etc.), is WithEvents
and Handles
usage preferable to RemoveHandler
and AddHandler
?
A related Stack Overflow question is Event handler and memory leaks.
It depends on what you're trying to achieve. If you have several event handlers which must handle events for various controls during the lifetime of a form/object then WithEvents and Handles is the easiest way to go. The language will do all of the dirty work for you in terms of setting up the event. On the other hand, if you tend to disconnect from events during the lifetime of the form, AddHandler and RemoveHandler are better options.
I prefer WithEvents/Handles in situations where it is applicable, because it better expresses what the code is supposed to be doing. One caveat with "WithEvents/Handles" is that any object which receives events from a longer-lived object should implement IDisposable and should set all its WithEvents variables to Nothing when it is disposed, to ensure all events are unwired. Detaching events when using AddHandler/RemoveHandler is just as necessary, but perhaps more obvious. When using WithEvents it's somewhat easier to forget.
BTW, I don't know of any way to automatically set all WithEvents variables to Nothing. It would seem a common enough requirement, but for whatever reason Microsoft didn't include such a feature in VB.
Depends what your doing really, if you want to dynamically attach / detach event handlers then using AddHandler/RemoveHandler is the way to go about it otherwise using Handles is perfectly fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With