I have a setup where two instances (A, B) is listening on a event on a third instance (C). A has also a reference to B.
When the event is fired on C, A receives it first and then directly disposes B (by design). In the dispose-method, B removes its listener on the event on C (-=). What happens next is that B still receives the callback from C, even though B has unsubscribed the event on C.
I guess this is expected since the invocation-list probably is built only once the event fires (when both listeners still exist) and is not rebuilt even though one instance happen to unsubscribe during the invocation-loop.
My question is why there isnt a secondary check before the event is raised, if the object is really still subscribing to the event or not? I guess this is bad for perfomance and its a very uncommon scenario. But if I want to implement this behaviour myself?
I've tried something like this but I'm not sure if this is all that's required (It seem to work though). How does the invocation-loop look like internally in C#?
foreach(var e in Test.GetInvocationList())
{
if (!Test.GetInvocationList().Contains(e)) continue;
e.DynamicInvoke(this, EventArgs.Empty);
}
There is no clean way via the invocation list, etc.
The easiest is to have B set an old-fashioned bool flag when it deregisters and do a top-level if(unregistered==true) return; in the event handler.