Reputation: 1436
Given the following...
public MyClass
{
public void MyClass()
{
var myWorkerClass = new MyWorkerClass();
myWorkerClass.DoSomething();
// and exit quickly
}
}
public MyWorkerClass()
{
public void DoSomething()
{
ThreadPool.QueueUserWorkItem(() =>
{
SomeLongRunningProcess();
});
}
public static void SomeLongRunningProcess()
{
// Something that takes a long time
}
}
When do MyWorkerClass and MyClass become eligible for garbage collection?
My thinking is the anonymous function in MyWorkClass.DoSomething() will be stored in the local variable declaration space of MyWorkerClass. This will be enough of a reference to keep them around until the thread has completed. Is this correct?
Upvotes: 3
Views: 843
Reputation: 16468
MyClass should be eligible for collection immediately. MyWorkerClass will become eligible for collection after SomeLongRunningProcess() completes (assuming aformentioned method references 'this', which it does not in your example).
As your code stands now, both instances are immediately eligible.
If you want MyClass or MyWorkerClass to hang around, reference it from within SomeLongRunningProcess or the closure that invokes it.
Upvotes: 2