Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

C# 

Unsubscribe from events, is it neccessary ?

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.
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.
https://github.com/Washi1337

"I'll tell you this UDP joke, and I don't care if you will get it or not."


Possibly Related Threads...
Thread / Author Replies Views Last Post
[C#] by gigajewFeb 3, 2018 07:31 PM 0 296 Feb 3, 2018 07:31 PM
Last Post: gigajew
[.NET] by SIM-1517404Mar 7, 2017 01:21 PM 10 355 Mar 7, 2017 01:21 PM
Last Post: SIM-1517404
[C#] by HVNCSPJan 11, 2016 11:27 AM 7 285 Jan 11, 2016 11:27 AM
Last Post: HVNCSP