调用计时器线程返回时线程不会停止

时间:2012-05-23 16:06:56

标签: c# multithreading

我创建了这个测试程序,以找出当计时器回调线程返回但新创建的线程仍在运行时会发生什么。我将在下面10次看到“In Work”,即使当timer_Elapsed返回时本地线程变量不再在范围内。将线程的“IsBackground”属性设置为true无效。

这是否因为GC尚未运行而发生?因此假设以这种方式创建的线程将完成是危险的,因为GC可以随时运行并清理线程吗?

我知道这是一个愚蠢的例子,但我最感兴趣的只是了解这里发生了什么,所以我知道要避免什么。谢谢!

public class Program
{
    static void Main(string[] args)
    {
        var timer = new Timer(500);
        timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
        timer.AutoReset = false;
        timer.Start();
        Console.ReadLine();
    }

    static void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        Console.WriteLine("In timer elapsed.  Kicking off a thread in new local thread and then immediately exiting.");
        var thread = new Thread(Work);
        thread.Start(); // but...this doesn't stop when the current thread exits!  
        Console.WriteLine("About to exit timer elapsed.");
    }

    static void Work()
    {
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine("In Work");
            Thread.Sleep(1000);
        }
    }
}

2 个答案:

答案 0 :(得分:3)

执行线程拥有对自身的引用。 GC永远不会终止一个超出其他地方范围的线程。

答案 1 :(得分:2)

MSDN表示一旦启动一个线程,就没有必要保留对Thread对象的引用。