Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage Collection with ThreadPool

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?

like image 661
HatAndBeard Avatar asked Dec 06 '25 05:12

HatAndBeard


1 Answers

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.

like image 178
Lilith River Avatar answered Dec 08 '25 19:12

Lilith River