Ricibob
Ricibob

Reputation: 7705

Nulling members in dispose to control memory usage

A list of objects A are held in a cache. At one point those objects are passed around and a property of A, B is used. B is a large data structure. A needs to be kept in the cache but at a certain point B is no required - and because its large we want to let it be garbage collected.

Would a Dispose method on A that set A.B=null enable the garbage collector to collect that object if nothing else holds references to B (i.e we would call Dispose on A when we no longer require B, or a using statement might be used to achieve the same effect).

In this context Dispose is being used to control the life time of a managed object i.e when it can be freed by the CG.

Upvotes: 1

Views: 59

Answers (1)

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131219

Dispose is always used to control the lifetime of a managed object - accessing an object after calling dispose is such a bad idea that many BCL objects will throw exceptions if you do. Having no references to an object is a prerequisite for garbage collection, but the GC is smart enough to detect graphs.

For example, if A is an orphan and nothing else holds a reference to B, then B is collected as well. On the other hand, if something else holds a reference to B then A isn't really an orphan and will not be collected.

Nulling a reference doesn't force a garbage collection, nor should you try to force a garbage collection. The garbage collector is smart enough to run a collection only if there is actual memory pressure, as deallocation is expensive.

UPDATE

It seems the actual question is "If I want to release A.B without actually releasing A, is it OK to do it by calling A.Dispose() ?` to which the answer is "No, never".

A.Dispose means A is dead for all intents and purposes. Better add a method called A.CloseB() that actually calls B.Dispose() then sets it to null and let the GC collect it when it becomes necessary.

Upvotes: 1

Related Questions