2012-05-23 115 views
1

我创建了此测试程序,以了解定时器回调线程返回时发生的情况,但新创建的线程仍在运行。即使当timer_Elapsed返回时,本地线程变量不再处于作用域中,我会在下面10次看到“In Work”。将线程的“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); 
     } 
    } 
} 

回答

3

正在执行的线程持有对自身的引用。 GC不会终止其他地方超出范围的线程。

+0

谢谢!这解释了它。把这个标记为答案,因为你是第一个,但你和帕切普的答案都是有帮助的。 – Eric

2

MSDN表示一旦线程启动,就不需要保留对该线程对象的引用。