为了更加清晰易懂,我简化了以下示例。但我在一个实际生产程序中遇到这个问题,无法看出它是如何工作的!
public class Test
{
static void Main()
{
Counter foo = new Counter();
ThreadStart job = new ThreadStart(foo.Count);
Thread thread = new Thread(job);
thread.Start();
Console.WriteLine("Main terminated");
}
}
public class Counter
{
public void Count()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Other thread: {0}", i);
Thread.Sleep(500);
}
Console.WriteLine("Counter terminated");
}
}
主程序启动计数器线程并终止主程序。计数器线程将继续运行,输出以下内容。
Main terminated
Other thread: 0
Other thread: 1
Other thread: 2
Other thread: 3
Other thread: 4
Other thread: 5
Other thread: 6
Other thread: 7
Other thread: 8
Other thread: 9
Counter terminated
我的示例程序表明,尽管调用类不再存在,但线程仍将完成。然而,我的理解是一旦一个类超出范围,它的资源最终将被垃圾回收清理。
在我的实际场景中,线程进行了长达1-2小时的大规模电子邮件发送。我的问题是“垃圾回收是否最终会终止该线程,还是GC知道该线程仍在处理?” 我的电子邮件线程是否总是运行到完成,或者存在异常终止的危险?
Thread.CurrentThread
中携带Thread
对象,并且它们当前运行的方法被认为是GC根(因此是GC发现对象是否仍有引用的起点)... 但是,是的,这是循环推理。 - xanatos