Is WithEvents / Handles better than Remove / AddHandler?

In terms of memory (delete added handler after use, etc.) is WithEvents and Handles , preferably RemoveHandler and AddHandler ?

Related question: Event handler and memory leak .

+7
event-handling
source share
3 answers

It depends on what you are trying to achieve. If you have several event handlers that must handle events for various controls throughout the life of the form / object, then WithEvents and Handles is the easiest way. The language will do all the dirty work for you in terms of setting up the event. On the other hand, if you want to disconnect from events throughout the life of the form, it is better to use AddHandler and RemoveHandler.

+4
source share

I prefer WithEvents / Handles in situations where it is applicable, because it better expresses what the code should do. One caveat with "WithEvents / Handles" is that any object that receives events from a longer-lived object must implement IDisposable and must set all WithEvents variables to Nothing when it is deleted so that all events are reset to zero. Disabling events when using AddHandler / RemoveHandler is necessary, but perhaps more obvious. When using WithEvents, it is somewhat easier to forget.

By the way, I do not know how to automatically set all WithEvents variables to Nothing. This would seem to be a fairly general requirement, but for some reason Microsoft did not include such a feature in VB.

+4
source share

Depends on what you are actually doing, if you want to dynamically attach / detach event handlers and then use AddHandler / RemoveHandler - this is a way around it, otherwise using descriptors is fine.

+1
source share

All Articles