Is it safe to replace all standard event handler to WeakEventManager or its variants?
Asked Answered
S

3

5

Standard event handler (with operator +=) is one of the memory leakage cause (if it is not unregistered/disposed (with -= operator)).

And Microsoft solved it with WeakEventManager and its inheritance like: PropertyChangedEventManager, CollectionChangedEventManager, CurrentChangedEventManager, ErrorsChangedEventManager and so on.

The simple example code with memory leakage is:

public class EventCaller
{
    public static event EventHandler MyEvent;
    
    public static void Call()
    {
        var handler = MyEvent;
        if (handler != null)
        {
            handler(null, EventArgs.Empty);
            Debug.WriteLine("=============");
        }
    }
}

public class A
{
    string myText;

    public A(string text)
    {
        myText = text;
        EventCaller.MyEvent += OnCall;

        // Use code below and comment out code above to avoid memory leakage.
        // System.Windows.WeakEventManager<EventCaller, EventArgs>.AddHandler(null, "MyEvent", OnCall);  
    }
    
    void OnCall(object sender, EventArgs e)
    {
        Debug.WriteLine(myText);
    }
    
    ~A()
    {
        Debug.WriteLine(myText + " destructor");
    }
}

void Main()
{
    var a = new A("A");
    var b = new A("B");
    EventCaller.Call();
    a = null;
    GC.Collect();
    EventCaller.Call();
}

The output is:

A
B
+++++++
A
B
+++++++

We can see that the destructor will not be called. But if we change (by commenting the unused code) from:

    EventCaller.MyEvent += OnCall;

to

    System.Windows.WeakEventManager<EventCaller, EventArgs>.AddHandler(null, "MyEvent", OnCall);  

And the output is:

A
B
+++++++
B
+++++++
A destructor
B destructor

After A is nulled then its event handler will not be called anymore. A and B will be disposed after not be used anymore without -= operator.

  1. Can I safely replace all += operator with System.Windows.WeakEventManager to avoid memory leakage due to probably missing event unregistration and saving code by should not implement IDisposable?

  2. If it is not really safe, what should I consider or notice?

Serendipity answered 4/4, 2017 at 7:39 Comment(0)
W
6

Can I safely replace all += operator with System.Windows.WeakEventManager to avoid memory leakage due to probably missing event unregistration and saving code by should not implement IDisposable?

Can you? Probably. Should you? Probably not. If you do have a strong reference to an event handler you should prefer unsubscribe from it if the publisher of the event lives longer than the subscriber of the event rather than replacing the strong reference with a weak event. There are side effects of using weak events. One of them is performance. Another is the semantic difference. You may want to refer to the following question and answers about why the implementation of events in the .NET Framework does not use the weak event pattern by default:

Why is the implementation of events in C# not using a weak event pattern by default?

There are certainly certain scenarios where you should use the weak event pattern. One such scenario is the data binding in WPF where a source object is completely independent of the listener object. But this doesn't mean that you should always use the weak event pattern. And it also doesn't mean that you should stop caring about disposing subscriptions in your applications.

Walden answered 4/4, 2017 at 10:42 Comment(0)
D
2

1) I would not take code saving as an argument to use the WeakEventManager instead of implementing IDisposable.

2) In case of the Weak event pattern, event handling will continue until the garbage collecor collects the listener. Unreferencing the listener does not stop event handling immediately as explicit unregistering of a strong referenced event handler in the Dispose pattern does.

3) See the Microsoft documentation concerning Weak Event Patterns

The weak event pattern can be used whenever a listener needs to register for an event, but the listener does not explicitly know when to unregister. The weak event pattern can also be used whenever the object lifetime of the source exceeds the useful object lifetime of the listener. (In this case, useful is determined by you.)

If you explicitly know when to unregister the listener, I would prefer the standard events and implement the Dispose pattern. From the event handlers point of view, explicit unregistration has the advantage that the event handling immediately stops while the weak event pattern continues to handle the events (which also could be CPU and memory consuming) until the garbage collector collects the listener.

Deshabille answered 4/4, 2017 at 8:32 Comment(2)
I agree that Unreferencing the listener doesn't stop the event handling immediately. But I think WeakEventManager has also Method RemoveHandler that will remove the event handler immediately. So if we have control when to remove the Event Handler we can do it also. But if we don't have it will do automatically even though later.Serendipity
Sure, there are scenarios where the Weak Event Pattern is the prefered solution to keep the source object completely independent of the listener. A common pattern ist the WPF data binding 'mm8' mentioned in his answer. But on the other hand there are good reasons why the Weak Event Manager is not the default event pattern of the .NET Framework. Strong references or weak references - both of them have their advantages and side effects. That's why I would decide depending on the specific situation which pattern to use.Deshabille
H
1

A specific case where you can't "blindly" substitute a weak event for a normal one was noted in a post by Thomas Levesque:

If you're subscribing to the event with an anonymous method (e.g. a lambda expression), make sure to keep a reference to the handler, otherwise it will be collected too soon.

So you can change it to weak as long as you keep a reference to the anonymous handler method / delegate in addition.

Hotel answered 12/2, 2021 at 15:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.