I have this class:
class Foo : IDisposable
{
SomeBigResource resource;
void UsingResource()
{
using(Bar bar = new Bar(SomeBigResource)
bar.doStuff();
}
void Dispose()
{
resource.Dispose();
}
}
void Function()
{
using (Foo foo = new Foo(new SomeBigResource))
foo.UsingResource();
}
The Bar object has exactly the same Dispose() function.
Will my SomeBigResource be released or is the GC smart enough to release it later on when the second using is done?
If both the
Disposemethods inFooandBarcallsDisposeon theSomeBigResourceobject, the method will be called twice. If the method is implemented correctly it will release the resources the first time and do nothing the second time.What you have is a confusion of responsibility, where both objects take responsibility for calling
Disposeon theSomeBigResourceobject. This is something that you want to avoid, as one object can’t know if the other object still needs the resource, so you want to put the responsibility in one place only.You should either make the
Fooobject responsible for the life cycle of the resource, or handle it outside of the objects completely. The latter makes more sense, as that’s where you create theSomeBigResourceinstance: