C# language: why WeakReference or Weak Event Pattern?

烂漫一生 提交于 2019-12-07 08:32:25

If I understand what you are asking, then there is a need for some clarification.

Otherwise, even if one of the event handler's object was assigned to null, the "orphan" object will still respond to the event - this will cause unexpected behavior.

Not really. This is not unexpected behavior. It is totally expected for the object to be called, if you do not unregister it explicitly.

The whole idea of the weak events is a safety net for not keeping objects in memory only because they are subscribed to an event. It has nothing to do with unregistering the object from the event when it goes out of scope.

If you need to do the later, either use IDisposable pattern and "using" construct for the subscribers, or do explicit unsubscribe.

I.e. weak events are solution for a very specific problem - to allow garbage collection of objects, which were subscribed to a long living object (like GUI or some static class).

Weak events are not about automatic unsibscribing from an even in the moment the object goes out of scope.

If the event subscriber and publisher both cooperate, it is possible to implement a reasonable weak-event pattern in .net without need for Reflection or other CLR tricks. It would be possible for an event subscriber to implement a weak-event pattern unilaterally if events' unsubscribe methods were required to function correctly if called by the finalizer thread, but unfortunately such an expectation is not reasonable when subscribing to events from an unknown class (e.g. an INotifyPropertyChanged). The trick would be for anyone who was really "interested" in an object to hold a strong reference to a wrapper, and for event handlers and other things to hold a reference to the object's "guts". The wrapper could hold a reference to both the guts and to an object with a Finalize method that would unsubscribe the event.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!