2013-02-17 32 views
2

在我的項目中,我創建了System.Timers.Timer對象,並且間隔設置爲10分鐘。 每10分鐘我就會收到一次事件。在這個事件處理程序中,我執行一些代碼。啓用System.Timers.Timer並且GarbageCollector

在執行此代碼之前,我將Enabled屬性設置爲false,因爲如果處理程序執行時間比下一個時間間隔長,另一個線程將執行耗盡的事件。

問題在這裏突然Elapsed事件停止。

我讀過一些文章,並懷疑啓用屬性設置爲false的時刻garbagecollector釋放計時器對象。

如果是正確的請告訴我解決方案。

下面是示例代碼:

public class Timer1 
{ 
    private static System.Timers.Timer aTimer; 

    public static void Main() 
    { 
     // Create a timer with a ten second interval. 
     aTimer = new System.Timers.Timer(10000); 

     // Hook up the Elapsed event for the timer. 
     aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); 

     // Set the Interval to 10min. 
     aTimer.Interval = 600000; 
     aTimer.Enabled = true; 

     Console.WriteLine("Press the Enter key to exit the program."); 
     Console.ReadLine(); 
    } 

    private static void OnTimedEvent(object source, ElapsedEventArgs e) 
    { 
     aTimer.Enabled = false; 

     // excutes some code 

     aTimer.Enabled = true; 
    } 
} 
+1

那篇文章的鏈接是什麼?這聽起來對我不正確。 GC收集仍然引用的對象的屬性設置爲某個值的原因是什麼?這在.NET中是非常罕見的GC行爲 – abatishchev 2013-02-17 10:29:01

+0

感謝您的回答。 請看下面的日誌,它表明「當Enabled屬性設置爲false時,它標記爲GC,因此它可以釋放定時器持有的資源。」http://forums.codeguru.com/printthread。 php?t = 342524 http://kvarnhammar.blogspot.com/2008/12/systemwindowsformstime-and-garbage.html http://stackoverflow.com/questions/14617336/garbage-collection-and-gchandle- alloc http://stackoverflow.com/questions/14216098/why-does-a-timer-keep-my-object-alive – user2080185 2013-02-18 07:36:15

回答

3

既然你已經在你的類指向一個領域你的計時器對象,GC將不會收集計時器對象。

但是,您的代碼可能會引發異常,並且這可能會阻止Enabled屬性再次變爲true。爲防止agianst這一點,你應該使用finally塊:

private static void OnTimedEvent(object source, ElapsedEventArgs e) 
{ 
    aTimer.Enabled = false; 
    try 
    { 
     // excutes some code 
    } 
    catch(Exception ex) 
    { 
     // log the exception and possibly rethrow it 
     // Attention: never swallow exceptions! 
    } 
    finally 
    { 
     aTimer.Enabled = true; 
    } 
} 
+0

感謝您的回答,我會盡量按照您的說法。 請看下面的日誌,它表明「當Enabled屬性設置爲false時,它標記爲GC,因此它可以釋放定時器持有的資源。」http://forums.codeguru.com/printthread。 php?t = 342524 http://kvarnhammar.blogspot.com/2008/12/systemwindowsformstime-and-garbage.html http://stackoverflow.com/questions/14617336/garbage-collection-and-gchandle- alloc http://stackoverflow.com/questions/14216098/why-does-a-timer-keep-my-object-alive – user2080185 2013-02-18 07:35:39

+0

@ user2080185這些鏈接都是在討論定時器對象,**超出scopt **但**不是垃圾收集**。但是你的情況恰恰相反。你的計時器**在範圍**中,你正在參考它。所以GC從不收集它,直到你**停止定時器**和**放棄參考**到定時器對象。這些帖子中的案例不適用於您的情況。 – 2013-02-18 07:53:47

相關問題