2012-05-23 119 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表示一旦線程啓動,就不需要保留對該線程對象的引用。