Göran Andersson said:
If you want to keep an object, keep the reference to it. The garbage
collector never collects objects that are reachable, regardless of how
long it was since you used it.
As soon as the garbage collector finds that an object is unreachable, it
can collect it.
This isn't necessarily true. Objects can sometimes be prematurely claimed
by the GC. Remember that the GC can only track references in managed
memory. So if you have passed a reference to an object off to unmanaged
memory then the GC may not properly detect that the object should not be
collected. The GC has a KeepAlive method just for this scenario. Pass your
object into KeepAlive at the point in your code where it is OK for the GC to
collect. That will insure that a managed reference is held to that object
up to the call to KeepAlive. A quick example:
object obj = new object
// pass the object off to some unmanaged memory
UnmanagedCall(obj);
// once we get this far it is OK for obj to be collected
GC.KeepAlive (obj); // this call insures that a managed reference is held
to this object at least to here
A very rudimentary example, most scenarios are more complex.