Garbage Collection

A

a.mustaq

Hi All,

When an object is not is used for a long time,
it will be removed by Garbage Collector. How can we avoid the Garbage
Collector not to remove the object though it has not been used for a
long time.
 
T

Tom Porterfield

Hi All,

When an object is not is used for a long time,
it will be removed by Garbage Collector. How can we avoid the Garbage
Collector not to remove the object though it has not been used for a
long time.


Look at the documentation for GC.KeepAlive()
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

Hi All,

When an object is not is used for a long time,
it will be removed by Garbage Collector. How can we avoid the Garbage
Collector not to remove the object though it has not been used for a
long time.

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.
 
T

Tom Porterfield

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top