new Thread() 和垃圾收集
我有以下代码:
new Thread(new ThreadStart(delegate()
{
while (true)
{
//something
}
})).Start();
垃圾收集器可以在 Thread
处于 Running
状态时完成此实例吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
CLR 跟踪所有正在运行的线程。只要存在对对象的引用,它们就不会被垃圾收集。由于 CLR 保留对所有正在运行的线程的引用,因此 GC 不会触及它们。
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.
不;正在运行的线程算作根。正在运行的线程将不会被收集,该线程的堆栈的活动部分引用的任何内容也不会被收集。
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.
线程不会被收集,因为每个正在运行、正在等待或挂起的线程本身都被 GC 用来决定什么是活动的(跟踪每个线程堆栈中的所有内容,跟踪所有这些对象引用的所有内容,然后跟踪这些对象引用的所有内容,等等,并且您已经确定了无法进行垃圾收集的所有内容)。
如果它是后台线程,则该线程可能会结束,因为当进程中的所有其他线程完成时,它将主动关闭。否则,唯一导致它死亡的事情是进程主动退出、异常(包括 ThreadAbortException )或它突破了 while 循环本身。
有一种情况在某些方面具有可比性,这可能就是您所想到的:
这是另一段代码,它导致另一个执行线程执行某些操作。在这种情况下,计时器确实可以在运行之前、其中一次运行期间或构造函数返回后的几乎任何时间进行垃圾收集。
这里重要的是,计时器没有单独的线程,并且线程甚至不“知道”计时器对象。由于该对象的最后一次访问已经发生,因此它符合收集条件。这与正在运行(或等待等)的单个线程的情况不同。
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 thewhile
loop itself.There's a case that's comparable in some ways, that may be what you are thinking of:
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.).
所有正在运行的计时器、线程、线程池和任务都被标记为根。因此,它们仅在完成(完成执行)时才会被垃圾收集,或者在应用程序关闭时被删除。
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.