In the following code:
public void f()
{
List l1<int> = new List<int>();
List l2<int> = new List<int>();
//.. populate l1 and l2
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object state)
{
// use l1 and l2
// force gc.collect l1 and l2?
}));
//..
}
l1 and l2 are Thread local very large lists. When do they become eligible for garbage collection? When the thread is done executing the block, do they become eligible?
Is it a good idea to force garbage collection of l1 and l2 when the thread is done with them?
thanks
First off, calling GC.Collect only schedules a garbage collection. If something is still being referenced, then it will still not be collected.
As to your answer, I believe that these will be collected once they are not referenced any longer, which would require that the delegate be completed and not referenced anymore.
So, if it is a simple usage, I believe that the delegate will be cleaned up when it completes, which will then allow the lists to be cleaned up
However, you might fall into a trap where the anonymous delegate is not cleaned up, but I think the ThreadPool should deal with this. If not, then you might be interested in this SO, especially Rory’s answer