Hi everyone,
I have a class (let's call it "X") that listens for Resize events on a
single Control (let's call it "C"). X should receive Resize events from
exactly one Control (not multiple Controls).
I have something like this in X:
C.Resize += delegate(object sender, EventArgs e) {
Control myControl = (Control)sender;
// do something with C's Location
};
Class X never maintains a strong reference to Control C and I don't want it
to because I don't want X to prevent C from being garbage collected. If C
goes out of scope and is eventually garbage collected, this will not affect
X's Resize handler. X will simply cease to receive Resize events for C,
which is fine.
Again, it's important that X *not* maintain a strong reference to C as I do
not want X to prevent C from being GCed.
So far, so good.
Now, sometimes I need class X to *stop* receiving Resize events on C and
instead receive Resize events on some other control (let's call it D). But
since X does not have a reference to C it cannot un-install its Resize
handler. In other words, X cannot tell C it is no longer interested in
Resize events. If X installs a Resize listener on D without uninstalling the
listener on C, it will receive Resize events for both C and D, which is
unacceptable.
The solution I'm considering is to maintain a weak reference in X to C using
System.WeakReference. This will allow X to remove its Resize handler on C
(if C has not been GCed) before installing a new listener on D.
Does this sound like a reasonable approach?
|