Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 470
Yohanes Nurcahyo Avatar asked Apr 04 '17 07:04

Yohanes Nurcahyo


People also ask

What is the use of weakeventmanager?

The WeakEventManager class enables you to leverage the weak event listener pattern by specifying the event to subscribe to, the source of the event, and event handler. You can use WeakEventManager<TEventSource,TEventArgs> as an alternative to implementing the IWeakEventListener interface and using a specialized WeakEventManager.

Is the event handler a method on the class?

When you define a component using an ES6 class, a common pattern is for an event handler to be a method on the class. For example, this Toggle component renders a button that lets the user toggle between “ON” and “OFF” states:

What is event handling in Spring Framework?

Event Handling in Spring is provided with the ApplicationListener interface along with ApplicationEvent class. Thus, every time an ApplicationEvent gets published to ApplicationContext notification is sent to Bean. a. A Standard of Event Handlers There are several standard events in Spring Framework which are as follow:

How to add a handler to a weak event in WPF?

AddHandler to add an handler on a event of a given source. It takes the name of the event as a parameters; It is done using reflection so you can have a little performance overhead using this object. Prior to WPF 4.5, every subscriber to a weak-event must implements the IWeakEventListener.


2 Answers

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.

like image 171
mm8 Avatar answered Sep 28 '22 16:09

mm8


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.

like image 20
Patrick Avatar answered Sep 28 '22 16:09

Patrick