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

后端 未结 2 942
孤街浪徒
孤街浪徒 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: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.

提交回复
热议问题