Hi Pachanga,
You won't ever know when the garbage collector will run. However, if you
had a situation where you wanted to be able to resurrect an object before
the garbage collector got to it, you could use weak references. I mention
it because it exists and is a possibility, but I make no assumptions as to
whether it is appropriate in your case. Before using it, you should learn
as much as you can about garbage collection. Here's a very simple example:
Test tst1 = new Test();
WeakReference wkTst = new WeakReference(tst1);
tst1 = null;
//GC.Collect();
Test tst2 = (Test)wkTst.Target;
if (tst2 != null)
{
Console.WriteLine("Test has not been GC'd");
}
else
{
Console.WriteLine("Test has been GC'd");
}
Uncomment the GC.Collect() line for a different result. BTW, you should
*not* use GC.Collect in your code. The garbage collector is optimized to
know when it should run and you could potentially slow your own code down by
using it yourself. This is simply an example to force the behavior of the
weak reference.
Here are a couple articles you can read to get a better understanding of how
Garbage Collection and Automatic Memory Management works:
http://msdn.microsoft.com/msdnmag/issues/1100/GCI/default.aspx
http://msdn.microsoft.com/msdnmag/issues/1200/GCI2/
Joe