On Mon, 30 Jun 2008 12:35:06 -0700, <He*************@googlemail.comwrote:
I've been considering that my objects should subscribe to an event via
a weak reference, however I've found several warnings that this
approach comes with concurrency considerations, like the fact that the
event handler method on the subscriber could be called and be
executing while the object is being garbage collected.
Can you be more specific? I don't see any way for a default-declared
event (i.e. no custom add/remove implementation) to be subscribed "via a
weak reference". Are you specifically implying that you'd also provide
custom add/remove implementations? What would the exact implementation of
this approach look like?
As for the rest of your question...
Not being super strong in the multithreaded department, I am having a
hard time coming up with other possibly problematic concurrency
considerations. I realize this question is quite vague, but I am not
even sure where to start educating myself on such topics.
Well, the whole point of a weak reference is to allow the garbage
collector to collect the object if necessary. There are a variety of
reasons that might happen, but they all pretty much come down to the same
thing: if the only reference to an object is in a WeakReference instance,
the object could be garbage collection. You always have to copy the
reference to a regular "strong reference" variable before you use it,
checking to make sure it's still valid.
Other than that, I don't see what "other possibly problematic concurrency
consideration" might exist. Seems to me that the one consideration about
the object being collected should complicate your life quite enough. :)
Anyone have any links or literature they can point me to?
Well, you should probably read the docs for the WeakReference class, as
well as the various articles on MSDN that provide more details regarding
how the garbage collection system works. Without a firm understanding of
those topics, I don't think you should be messing around with weak
references.
That said, for that matter it's not really clear to me what you hope to
gain by using a weak reference for your event subscriptions. Sounds
pretty odd to me.
Pete