1. Will garbage collector gets invoked if Gen 0 and Gen 1 is not under pressure ?
If there is enough space in Generation0
and Generation2
, then Garbage Collector will not be invoked.
If there is enough space in Generation0
and Generation2
, then it means that that there is enough space to create new objects and there is no reason to run Garabage Collection.
2. Will it go to Gen 2 when it has released Gen 0 or Gen 1 memory ?
If the object is survived after Garbage Collection in Generation1
and in the Generation1
, then the object will be moved to Generation2
.
3. If so what’s the better way to handle this ?
To destroy an object from heap, you should just delete references of this string. Your string
variable which has xml values should not be static
to be garbage collected.(read more about roots)
Try to use compact GCSettings.LargeObjectHeapCompactionMode
:
GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect();
This will compact the Large Object Heap when the next Full Garbage Collection
is executed. With GC.Collect()
call after the settings been applied, the GC gets compacted immediately.
Try to use WeakReference
:
WeakReference w = new WeakReference(MyLargeObject);
MyLargeObject = w.Target as MyLargeClass;
MyLargeClass MyLargeObject;
if ( (w == null) || ( (MyLargeObject=w.Target as MyLargeClass) == null) )
{
MyLargeObject = new MyLargeClass();
w = new WeakReference(MyLargeObject);
}
This article gives is very useful to you about Garbage Collection
and the article is written in plain English.