简体   繁体   中英

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

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?

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.

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.

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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM