Expired delegate (events)

J

Jon Davis

When an object goes out of scope, do all the event handlers automatically
get removed, or must this be done manually to ensure that the object
succeeds in being disposed of?

Thanks,
Jon
 
L

Lee Alexander

If the object is attached to another one that is not collectable then it
will also be marked as *not* collectable. So in general yes you should
remove your handler from the event if you don't want your object to hang
around.

Regards
Lee
 
S

Simon Trew

The problem I think is that the publisher of an event is not generally the
one that can make the decision about whether the subscriber is collectable
or not-- that's a job more properly left to the subscriber. The current
event model is thus that the subscriber is somehow informed that the
publisher (form) would like to go away and it can then unsubscribe to break
the circular reference.

It would be quite easy to implement a WeakDelegate/WeakMulticastDelegate
where the target was a WeakReference, this would give you the behavior you
wanted. Someone is bound to reply that this is not possible as Delegate and
MulticastDelegate cannot be derived from (in C#). But you could make your
own separate classes. If I were to do this, actually I would allow the
WeakMulticastDelegate to have a combination of normal Delegate and
WeakDelegate members in its invocation list.

S.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top