On Mar 30, 1:52 pm, "JS" <jnospams...@gmail.comwrote:
I have an application with many user controls and forms which display
measurements in whatever the current unit system is. The current unit
system is kept in my 'Units' static class as Units.CurrentSystem. I
also have an event in the Units class called
Units.CurrentSystemChanged. My controls hook into this event (usually
in their OnLoad() method). However, I am not quite sure where to
unhook the event. I could do it in Dispose(), OnHandleDestroyed() or
somewhere else. I'd like to establish a pattern for doing this type
of thing in my application so if anyone has a comment I would
appreciate hearing it.
You have two choices.
1. The low-tech solution is to un-subscribe from the even in the
Form's Dispose method. As all Forms run with .Show() are Disposed when
the user closes them, and all code that uses .ShowDialog() is supposed
to Dispose the form afterward, this will work.
2. The high-tech solution is to subscribe to the event via a weak
reference delegate. You have to build this yourself (unfortunately),
but it allows your form to subscribe to the event and say, in effect,
"This subscription doesn't count where garbage collection is
concerned."
In your case, door #1 is probably the best. However, if you find your
forms subscribing to more and more static events (as I did) then the
second option becomes the simpler of the two.