-1

I have view object that initializes another object, creditCard Object, and register to an event that the creditCard is raising. If the view object will have no reference to it. Will it be garbage collected? or do I have to unsubscribe in order for that to happen?

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • its not related to view object only. `creditCard` should have no reference anywhere in your program to be gc`ed – M.kazem Akhgary Nov 10 '16 at 07:12
  • See also https://stackoverflow.com/questions/5103675/garbage-collection-and-local-variables-to-whose-events-a-control-has-subscribed, https://stackoverflow.com/questions/11507632/net-object-events-and-dispose-gc, https://stackoverflow.com/questions/10853300/in-c-do-events-keep-a-reference-to-the-entire-class-where-the-call-back-method, https://stackoverflow.com/questions/13372479/will-this-event-handler-code-cause-a-memory-leak, https://stackoverflow.com/questions/14428402/why-this-does-not-cause-a-memory-leak-when-event-is-not-unsubscribed, ... – Peter Duniho Nov 10 '16 at 08:44
  • ... and https://stackoverflow.com/questions/15370527/garbage-collection-of-unreferenced-object-with-live-event-handler – Peter Duniho Nov 10 '16 at 08:44
  • Note that your question as asked is too broad and unanswerable, because you haven't explained the lifetime of the `creditCard` object. As all of the other discussion on Stack Overflow explains, a subscriber to an event is referenced, which _may_ prevent it from being collected. But if the object with the event is itself not reachable, both the publisher and subscriber of the event can be collected. Without a good [mcve] illustrating your question, no one can tell you what you actually need to do. It just depends on the situation. – Peter Duniho Nov 10 '16 at 08:46

2 Answers2

0

You will need to unsubscribe for the object to be garbage collected.

"The cause is simple to explain: while an event handler is subscribed, the publisher of the event holds a reference to the subscriber via the event handler delegate (assuming the delegate is an instance method)." - https://stackoverflow.com/a/4526840/283787

Community
  • 1
  • 1
openshac
  • 4,966
  • 5
  • 46
  • 77
0

When your creditCard object subscribes to event ti will reference your view object. For example creditCard.Event += MyEvent... and this is equivalent to creditCard.Event += this.MyEvent... where this will be referencing theview object so you have to unsubscribe in order to be garbage collected.

Milen
  • 8,697
  • 7
  • 43
  • 57