• Status: Solved
  • Priority: Low
  • Security: Public
  • Views: 62
  • Last Modified:

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?
0
deleyd
Asked:
deleyd
  • 4
  • 3
1 Solution
 
Éric MoreauSenior .Net ConsultantCommented:
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).
0
 
it_saigeDeveloperCommented:
It is also generally good practice to unsubscribe from events when you no longer will use them.

-saige-
0
 
deleydAuthor Commented:
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?
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
it_saigeDeveloperCommented:
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-
0
 
deleydAuthor Commented:
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

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

-saige-
0
 
deleydAuthor Commented:
ClassB is not IDisposable.
0
 
it_saigeDeveloperCommented:
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-
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now