![]() |
|
[C#] Unsubscribe from events, is it neccessary ? - Printable Version +- Hack Forums (https://hackforums.net) +-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444) +--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151) +---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118) +---- Thread: [C#] Unsubscribe from events, is it neccessary ? (/showthread.php?tid=5845771) |
Unsubscribe from events, is it neccessary ? - darkdoctor - Jun 7, 2018 Hello Guys. I am confused a lil bit with the events. Lets say I have a class A and B. Class B has one events which class A has been subscribed on. When the class B has run out of scope and there is no reference to class B, except an event. Should I unregister the event from class A or the GC will do it ? Thanks. RE: Unsubscribe from events, is it neccessary ? - Washi - Jun 7, 2018 Good question. Let's call the object exposing the event the publisher (class B), and the object containing the handler the subscriber (class A). The subscription of the handler does not affect the timing of the garbage collection of the publisher. Therefore, it is not required for the subscriber to unsubscribe to the publisher's event to mark the publisher for garbage collection. However, if the publisher is a long-living object, it may very well be the case that the subscriber is being kept alive and not garbage collected because of it. Especially when the event is static, this can be quite dangerous. |