Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I implement a C# destructor (aka finalizer) to unsubscribe from a system event? [duplicate]

Tags:

c#

.net

mef

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?

like image 947
logeeks Avatar asked Dec 12 '25 06:12

logeeks


1 Answers

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.

like image 78
Rob Ocel Avatar answered Dec 13 '25 20:12

Rob Ocel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!