Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WithEvents/Handles better than Remove/AddHandler?

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.

like image 517
serhio Avatar asked Feb 05 '10 16:02

serhio


3 Answers

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.

like image 110
JaredPar Avatar answered Nov 18 '22 15:11

JaredPar


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.

like image 4
supercat Avatar answered Nov 18 '22 14:11

supercat


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.

like image 1
David Avatar answered Nov 18 '22 16:11

David