user2538115
user2538115

Reputation: 1

How resources will be free by Dispose or Finalize?

I have three classes. Class1, Class2 and Class3. I have circular dependency(class1 to class2, class2 to class3,class3 to class1). In this case how resources will be free by dispose method or finalize()?

Upvotes: 0

Views: 35

Answers (1)

Martin Liversage
Martin Liversage

Reputation: 106816

When you implement IDisposable on an object you also make a decision of ownership. If Class1 has a reference to Class2 you have to decide if Class1 owns Class2 or if it just stores a reference. If Class1 owns Class2 and Class2 is IDisposable then Class1 should also implement IDisposable and Class1 should call Dispose on the Class2 reference in the Dispose method, but only when called explicitely - not when finalized.

Because IDisposable also defines an ownership hierarchy you cannot have circular dependencies when disposing. Of course Class1 can own Class2 that owns Class3 and Class3 can have a reference to Class1 but because Class3 doesn't own Class1 it should not call Dispose on the reference when disposed.

During finalization a class that implements IDisposable should only release unmanaged resources and not call Dispose on classes that it owns because these instances may already have been finalized by the garbage collector.

Upvotes: 2

Related Questions