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

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

提交回复
热议问题