I was refering MSDN tutorial on weak events. I understood the basics. I am working on a non-WPF project and my class is exposing certain events. My question is that does the weak events completely replace old event pattern? Is it good to use it every classes that is exposing events? What are the side effects of using weak events liberally?
Based on the reading I have done, there does not appear to be any specific negatives to using WeakEvents, except for the fact that it is more verbose to do so. Additionally, you should be able, in most cases, to manually unregister from events when you no longer need them. In some cases, this won't be possible. For example, the MSDN page you reference mentions when you should use WeakEvents:
http://msdn.microsoft.com/en-us/library/aa970850.aspx
Certain scenarios inherently lend themselves to the application of the weak event pattern. One such scenario is data binding. In data binding, it is common for the source object to be completely independent of the listener object, which is a target of a binding. Many aspects of WPF data binding already have the weak event pattern applied in how the events are implemented.
The only person who has presented any type of negative to them is this blog:
http://blog.catenalogic.com/post/2011/11/23/A-weak-event-listener-for-WPF-Silverlight-and-Windows-Phone-7.aspx
There are a few downsides about using a weak event listeners in general:
- It’s notation is ugly, the “original” .NET way looks way better
- You have to name the event by string, that sucks (if you know a better way, contact me!)
- It can only handle events with a handler of EventHandler
- You become a lazy developer not caring about subscriptions
Essentially, they should be used for events that your objects will subscribe to for the entire length of their existence, and only disconnect from when the objects are disposed. For everything else, using the traditional events and registering/unregistering the events manually is preferred.
There are two issues that must be considered with weak events:
See more details at The Weak Event Pattern is Dangerous.
See this source code that illustrates this issue using the MvvMCross messaging plugin as a weak event manager.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With