【发布时间】:2013-02-17 10:21:11
【问题描述】:
在我的项目中,我创建了System.Timers.Timer 对象,并且间隔设置为 10 分钟。
每 10 分钟,我就会收到经过的事件。在这个事件处理程序中,我正在执行一些代码。
在执行此代码之前,我将Enabled 属性设置为等于false,因为如果处理程序的执行时间比下一个时间间隔长,则另一个线程将执行已逝事件。
这里的问题是Elapsed 事件突然停止。
我已经阅读了一些文章并怀疑设置为 false 垃圾收集器的时刻启用属性会释放计时器对象。
如果正确请告诉我解决方案。
下面是示例代码:
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 行为
-
感谢您的回答。请查看以下日志,这些日志表明“当 Enabled 属性将其设置为 false 时,其标记为 GC,因此它可以释放计时器持有的资源”forums.codeguru.com/printthread.php?t=342524kvarnhammar.blogspot.com/2008/12/…stackoverflow.com/questions/14617336/…stackoverflow.com/questions/14216098/…
标签: c# .net timer garbage-collection