4

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

user236215
  • 7,278
  • 23
  • 59
  • 87

1 Answers1

4

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

Community
  • 1
  • 1
Justin Pihony
  • 66,056
  • 18
  • 147
  • 180
  • great thanks for clarifying. I will hope ThreadPoolWorker behaves properly. – user236215 Nov 20 '12 at 04:26
  • Yeah, I'm also thinking that capturing the variables may extend the life of l1 and l2 until the delegate finishes execution.. not sure though. – Lews Therin Nov 20 '12 at 04:26
  • @LewsTherin Well, as to capturing the variables, it DEFINITELY will extend the life. It is more about if the anonymous delegate needs cleaned. – Justin Pihony Nov 20 '12 at 04:27
  • I don't worry about extending the life but more about ThreadPool holding on to the delegate and l1 and l2 for long time. That will have affects on memory footprint. – user236215 Nov 20 '12 at 04:29
  • Yeah... that probably depends on whether Threadpool decides to reuse the WaitCallback object? Anyway, sounds interesting.. good luck! :P – Lews Therin Nov 20 '12 at 04:30
  • @user236215 Here is a SO that has another person verifying that the ThreadPool will clean up: http://stackoverflow.com/questions/1755597/c-do-i-need-to-dispose-a-backgroundworker-created-at-runtime – Justin Pihony Nov 20 '12 at 04:32