0

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()?

1 Answers1

2

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.

Martin Liversage
  • 104,481
  • 22
  • 209
  • 256
  • I wish .NET had made some distinction between references that encapsulate ownership and references that don't. While there would be no way to avoid manual `Dispose` coding in some cases, it really should be possible to have a type specify that it "owns" certain fields, and have the compiler provide a way to `Dispose` all of the fields that an object owns whose types implement `IDisposable`. – supercat Jul 02 '13 at 15:33