Is there a way to force garbage collection?

Yes. Set all references to null and then call System.GC.Collect().

If you need to have some objects destructed, and System.GC.Collect() doesn't seem to be doing it for you, you can force finalizers to be run by setting all the references to the object to null and then calling System.GC.RunFinalizers().

Showing Answers 1 - 3 of 3 Answers

Guru

  • Apr 13th, 2006
 

It is not necessary to set all references to null.  If you set all references to null then GC will consider for collecting it, provided it should not be G2.  Otherwise you can force the GC to collect the references which is set to 'null', then GC will collect the null referenced objects and it should be in G0 or G1 state.

  Was this answer useful?  Yes

Sivakrishna

  • Nov 12th, 2007
 

GC.Collect();

It is recomended that you should not forcefully call the GC. GC does it in the optimal way, since it knows the inner details like which object actually created inner objects.

But some case you may need to force GC to free the scarce memory resouces. Better to use IDisposable interface, call dispose method. Dont forget to call GC.SupressFinilazer.

  Was this answer useful?  Yes

As others have mentioned forcing garbage collection is ill advised and really should not be necessary with proper implementations of IDisposable.  One could probably argue that in .net < 2.0 the GC was a tad lazy, and also with certain APIs the implementation of IDisposable is out of your control, but forcing collection was still a performance killer and risky in 90% of situations.


Also, not only is setting a variable to null not necessary, it does nothing in respects to memory (de)allocation.  The primary determinant of an object reference being eligible for garbage collection is scope.  If you force garbage collection while variable A is out of scope, and B is in scope but set to null, only A will be "collected", regardless of its latest assignment.

The reason for this is that scope is fully established at compile time and is completely unconditional and impossible to modify at runtime.  The choice of whether or not to set a reference to null is conditional, dependent on runtime.  This allows the GC to create a "timeline" and "triggers" for garbage collection at compile time; a huge performance gain. 

public class Foo
{
private string a;

protected string Bar(string input)
{
string b = "42";
a = input;

return a + b;
}

public void Main()
{
string output = Bar("The answer is ");
Console.WriteLine(output);

a = null;
output = null;
GC.Collect();

// the resources allocated for 'a' and 'output' would NOT be collected.
// b's resources, along with input's resources would be collected. 
}
}

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions