A while back when I was working on the publish property page, I need to unhook an object from it's event handlers. That object was declared with Dim WithEvents and the handlers were wired up with Handles clauses on the methods of the object. While I love this event paradigm, I didn't know the right way to unhook the handlers in this case. This was causing the object to remain in memory and bad things were happening.


So I cracked open Ildasm (a key tool for any hardcore VB developer) to figure out how the handles clause wires up the events (and how it unhooks them). It turns out that every WithEvents field is compiled into a property by the VB compiler. In the setter of that property, a null value will cause the events hooked up via Handles to be unhooked and setting another value will do the same for the old instance and hook up the new instance.


Armed with my ildasm evidence, I walked down the hall and talked to a compiler dev to confirm my theory. I told him what I thought was going on and he thought for a second and replied, "Yeah, that'll work." So there you go. Use the super-handy WithEvents/Handles syntax and use this little trick when you need to manage your objects carefully.


I hope to get another tech post up tomorrow and make it 3 days in a row :)