user11937
user11937

Reputation:

Spinning up a new Thread - do I need to care about garbage collection

I'm having a bit of a brain-freeze so I thought I'd throw this out there to the collective genius of SO...

I have an event that is raised (this will be on the thread of the "raiser") and I consume it.

However, once I am handling this event, I need to fire off another thread to perform the workload that the event signified. So, I'm using:

private void MyEventHandler(object sender, EventArgs e)
{
    Thread t = new Thread(new ThreadStart(MyHandler));
    t.Start();
}

private void MyHandler()
{
    DoStuff(); // takes a long time
}

My question is: Do I need to be concerned about the lifecycle of the variable t? i.e. Can t be garbage collected, thus aborting the work being performed in DoStuff()?

Upvotes: 8

Views: 2817

Answers (3)

gfelisberto
gfelisberto

Reputation: 1723

If I understand correctly you are afraind that the Thread may be Garbage Collected while it is still working. And that would happen because after the method exits there is no reference to t.

But you need not to be afraid. As long as the thread is running there will be a reference to it and the thread will not be garbage collected.

Upvotes: 1

Gregory A Beamer
Gregory A Beamer

Reputation: 17010

Can the thread work and objects be GCed? Yes. Will it happen automatically? Once the thread is complete.

But if this is a really long process that does not indicate failure back to the thread, it could potentially lock up resources indefinitely.

In these cases, a callback mechanism may be a better solution to leaving a thread open for an indefinte period.

Upvotes: 0

Jim Mischel
Jim Mischel

Reputation: 133995

There's no particular reason that you need to keep track of the Thread variable. The GC won't kill the thread when t goes out of scope.

I don't know how long "a long time" is, but you might be better off using something like ThreadPool.QueueUserWorkItem. That is:

private void MyEventHandler(object sender, EventArgs e)
{
    ThreadPool.QueueUserWorkItem(MyHandler);
}

private void MyHandler(object state)
{
    DoStuff();
}

Upvotes: 8

Related Questions