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

后端 未结 2 940
孤街浪徒
孤街浪徒 2020-12-19 17:36

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

相关标签:
2条回答
  • 2020-12-19 18:01

    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.

    0 讨论(0)
  • 2020-12-19 18:20

    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.

    0 讨论(0)
提交回复
热议问题