Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...