【发布时间】:2015-05-18 20:29:47
【问题描述】:
为了清楚起见,我简化了下面的示例,但我在现场制作程序中遇到了这个问题,我看不出它是如何工作的!
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对象“在”自身“内部”,在Thread.CurrentThread中,和它们当前的运行方法被认为是 GC Root(因此 GC 发现对象是否仍然具有参考)...但是,是的,这是一个循环推理。 -
类不会超出范围。对象不会超出范围。变量超出范围(这很容易理解 - 这意味着变量不再存在。如果变量是引用,它不会对它引用的对象做任何事情)。
标签: c# .net multithreading