Avatar of deleyd
deleyd
Flag for United States of America asked on

Is it necessary to unsubscribe from event on Dispose() in this case?

classA creates an instance of classB, stores the classB instance as a field, and subscribes to a classB generated event.

ClassA is IDisposable. ClassB is not IDisposable.

On dispose of classA, is it necessary for classA to unsubscribe from the classB event?
.NET ProgrammingC#

Avatar of undefined
Last Comment
it_saige

8/22/2022 - Mon
Éric Moreau

If an object is disposable, it is really a good practice to call the Dispose method (or to bundle the usage with a USING structure).
ASKER CERTIFIED SOLUTION
it_saige

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
deleyd

ASKER
Is it necessary to unsubscribe if classB is one classA created, and classA is being disposed? Will the reference held by classA prevent classB from being garbage collected?
it_saige

No it won't but say that the subscription to classB's event uses unmanaged resources, you already stated that classB does not implement IDisposable, so the only way to sensible way to free those unmanaged resources would be by unsubscribing the event, as long as the event unsubscription process handles the freeing of those unmanaged resources, which from a design standpoint, is sensible.

-saige-
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
deleyd

ASKER
How would I determine if "the subscription to classB's event uses unmanaged resources"?

It's just something like (in ClassA):
classB.MyEvent += this.MyEventHandler;

Open in new window

it_saige

You would have to review the code of classB in order to determine if it used any unmanaged resources.

-saige-
deleyd

ASKER
ClassB is not IDisposable.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
it_saige

A class, correction; an Object, does not *have* to implement IDisposable in order to consume or declare unmanaged resources.

Another way to look at it, regardless of the implementation, it's just a good practice.

-saige-