问题描述
为了清楚起见,我简化了下面的示例,但是我在一个实时生产程序中遇到了这个示例,但看不到它是如何工作的!
I simplified the example below for the sake of clarity, but I came across this in a live production program and I cannot see how it would be working!
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");
}
}
主例程启动计数器线程,并且主例程终止.无论给出以下输出,计数器线程都会继续运行.
The main routine starts the counter thread and the main routine terminates. The counter thread carries on regardless giving the following output.
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
我的示例程序演示了,尽管调用类不再存在,但线程可以保留到完成.但是,我的理解是,一旦类超出范围,其资源最终将通过垃圾回收整理.
My example program demonstrates that although the calling class no longer exists, the thread survives to completion. However, my understanding is that once a class is out of scope, its resources will eventually be tidied up by garbage collection.
在我的现实生活场景中,该线程进行大量的1-2个小时的电子邮件发送.我的问题是垃圾回收将最终杀死线程还是GC知道线程仍在处理"?我的Emailing线程会一直运行到完成状态,还是存在异常终止的危险?
In my real life scenario, the thread does a mass Emailing lasting 1-2 hours. My question is "Would garbage collection eventually kill off the thread or will GC know that the thread is still processing"? Would my Emailing thread always run to completion or is there a danger it will terminate abnormally?
推荐答案
因此,即使未引用Thread
对象,该线程仍将运行.
So even if the Thread
object is unreferenced, the thread will still run.
这篇关于当原始类超出范围时,线程会发生什么情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!