当原始类超出范围时,线程会发生什么情况 [英] What happens to a thread when the original class goes out of scope

查看:82
本文介绍了当原始类超出范围时,线程会发生什么情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了清楚起见,我简化了下面的示例,但是我在一个实时生产程序中遇到了这个示例,但看不到它是如何工作的!

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?

推荐答案

来自 System.Threading.Thread

启动线程后,不必保留对Thread对象的引用.线程将继续执行,直到线程过程完成为止.

It is not necessary to retain a reference to a Thread object once you have started the thread. The thread continues to execute until the thread procedure is complete.

因此,即使未引用Thread对象,该线程仍将运行.

So even if the Thread object is unreferenced, the thread will still run.

这篇关于当原始类超出范围时,线程会发生什么情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆