Link to home
Create AccountLog in
Avatar of deleyd
deleydFlag 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?
Avatar of Éric Moreau
Éric Moreau
Flag of Canada image

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
Avatar of it_saige
it_saige
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of 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?
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-
Avatar of 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

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

-saige-
Avatar of deleyd

ASKER

ClassB is not IDisposable.
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-