new Thread() and Garbage Collection

2019-01-18 11:13发布

I have the following code:

new Thread(new ThreadStart(delegate()
{
    while (true)
    {
        //something
    }
})).Start();

Can garbage collector finalize this instance of Thread while it is in the Running state?

4条回答
一夜七次
2楼-- · 2019-01-18 11:19

All running timer, threads, thread pool and tasks are marked as root. So they will be garbage collected only when they're done (finished executing) or will be deleted when the application closes.

查看更多
Anthone
3楼-- · 2019-01-18 11:22

The thread won't be collected, because each running, waiting or suspended thread is itself used by the GC to decide what is alive (trace everything in every thread's stack, trace everything referenced by all of those objects, then everything referenced by those, and so on, and you've identified everything that can't be garbage collected).

The thread could end, if it was a background thread, because then it'll be actively shut down when all other threads in the process finish. Otherwise the only thing that'll cause it to die is the process being actively exited, an exception (including ThreadAbortException) or it breaking out of the while loop itself.

There's a case that's comparable in some ways, that may be what you are thinking of:

var timer = new System.Threading.Timer(someCallback, null, new TimeSpan(0, 0, 5), new TimeSpan(0, 0, 5));
int someResult = doingSomethingElse();
doSomethingElseThatTakesLongerThan5Seconds();

This is another piece of code that causes another thread of execution to do something. In this case, the timer can indeed be garbage collected before the run, during one of the runs, or pretty much any time after the constructor returns.

The important thing here is that there isn't an individual thread for the timer, and the thread doesn't even "know" about the timer object. Since the last access of the object has since happened, it's eligible for collection. This is different to the matter of an individual thread that is running (or waiting, etc.).

查看更多
疯言疯语
4楼-- · 2019-01-18 11:23

The CLR keeps track of all running threads. As long as there are references to objects they won't be garbage collected. And since the CLR keeps a reference to all running threads the GC won't touch them.

查看更多
疯言疯语
5楼-- · 2019-01-18 11:25

No; running threads count as roots. A running thread will not be collected, nor will anything referenced by the active part(s) of the stack for that thread.

查看更多
登录 后发表回答