Search code examples
c#wpfweakeventmanager

How can I determine if a source is being listened to by a target when using the weak event manager


I am using the weak event manager in my WPF app to hook up a source of an event to a target, using the XXXEventManager.AddListener(source, this); call. However, I have noticed that my code sometimes hooks up the same source and target more than once. This looks like it causes multiple events to be raised / handled that are effectively the same (i.e. one for each hook up). Is it possible to determine if the target is already hooked up to the event source by interrogating the WeakEventManager (or adding functionality to it) or will I have to implement my own list on the target?

Also, what's the accepted method for calling RemoveListener if the event hook up should be present for the lifetime of the source? I've heard that using a finalizer is not good practice because it causes problems with garbage collection. Is this accurate?


Solution

  • Well you could check with GetInvocationList if the Eventmanager is already attached. Check if it is already attached with that manager with a specific target on the other hand i don't know if thats possible. When looking at the PropertychangedEventManager though, it is perfectly fine to add multiple listeners to one manager with one target(distinguished with different property names)

    For me the correct way of calling RemoveListener is to use IDisposable. The problem with the finalizer is that your object lives longer, because it will be on the finalizer queue, and might get events at that time(not sure about that). Maybe this will help