Lets says we have 2 objects, Broadcaster and Listener. Broadcaster has an event called Broadcast to which Listener is subscribed. If Listener is disposed without unsubscribing from the Broadcast event it will be retained in memory because of the event delegate referencing it that Broadcaster contains.
What I’m curious about is if Broadcaster is disposed without Listener unsubscribing or Broadcaster setting Broadcast = null will Broadcaster be retained in memory?
I have not been able to locate anything with a hard answer to this question except one blogger who believes that not setting the event to null will keep the source in memory (found here).
I’d like to hear an explanation of why or why not.
Thanks.
Note that delegates don’t keep the publisher alive (they only keep the target=subscriber alive), so no number of subscriptions will (by themselves) keep the broadcaster alive. As such, from this perspective it doesn’t matter whether it is disposed or not. When there are no items referencing the broadcaster (and the event-subscriptions don’t matter for this), it will be eligible for collection.
Essentially, a delegate is a (list of) pair(s) of
MethodInfoandobjectreferences; the method to call, and the object to invoke as “arg0” (akathis). It simply doesn’t have a reference to the object raising the event.Here’s evidence that a listener does not keep the source alive; you should see that “Source 1” gets collected, even though we still have the matching listener that is subscribed. As expected, “Listener 2” does not get collected, since we still have the matching broadcaster: