2

I can subscribe to buttons click events like this:

button.Click += (sender, ev) => { /* do something! */ };

MSDN docs says this:

If you will not have to unsubscribe to an event later, you can use the addition assignment operator (+=) to attach an anonymous method to the event.

How can I determine if I "will not have to unsubscribe to an event later"? If I am in a class X and button is referenced in X and nowhere else, then can i safely use a lamdba without unsubscribing?

d370urn3ur
  • 1,736
  • 4
  • 17
  • 24
  • 1
    This is very much based on the flow of your code. You will want to unsubscribe in cases where you either don't want to receive any notifications of event happening, or you no longer want to use the given class which registered to the event. – Yuval Itzchakov Oct 15 '15 at 12:05
  • You probably want to read: [Is it bad to not unregister event handlers?](http://stackoverflow.com/questions/1061727/is-it-bad-to-not-unregister-event-handlers). – bokibeg Oct 15 '15 at 12:10
  • If you want to subscribe to events (i.e. you always want this code to run when you click the button) for the lifetime of your application, then you can do it this way. – DavidG Oct 15 '15 at 12:10
  • My concern is that it could create a memory leak by having a circular reference, I am specifically thinking of the case where I have a Page that creates and owns a ViewModel and the ViewModel has an event handler that the Page then subscribes to. In this case, if the Page gets removed, will it cause a memory leak? – d370urn3ur Oct 15 '15 at 12:13
  • If the page subscribes to the event handler and you remove that page, then yes, the viewmodel will keep it alive. – Yuval Itzchakov Oct 15 '15 at 12:16
  • That is, if something else keeps the viewmodel alive (if the viewmodel is a singleton for instance). Circular dependencies don't cause memory leaks in the .NET runtime – Kevin Gosse Oct 15 '15 at 12:20

0 Answers0