在我的項目中,我創建了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;
}
}
那篇文章的鏈接是什麼?這聽起來對我不正確。 GC收集仍然引用的對象的屬性設置爲某個值的原因是什麼?這在.NET中是非常罕見的GC行爲 – abatishchev 2013-02-17 10:29:01
感謝您的回答。 請看下面的日誌,它表明「當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