在我的项目中,我创建了System.Timers.Timer对象,间隔设置为10分钟。每10分钟,我就会得到一个流逝的事件。在这个事件处理程序中,我正在执行一些代码。
在执行这段代码之前,我将Enabled属性设置为false,因为如果处理程序的执行时间比下一个时间间隔长,则另一个线程将执行elapsed事件。
这里的问题是Elapsed事件突然停止。
我读过一些文章,怀疑moment enabled属性设置为false garbagecollector会释放timer对象。
如果是正确的,请告诉我解决方案。
以下是示例代码:
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;
}
}发布于 2013-02-17 18:29:50
由于您的类中有一个字段指向timer对象,因此GC不会收集timer对象。
但是您的代码可能会引发异常,这可能会阻止Enabled属性再次变为true。为了防止这一点,你应该使用一个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;
}
}发布于 2013-02-17 18:31:18
您可以设置同步对象,在这种情况下,流逝将只发生在该对象的所有者线程上,不具有并发性。这里发布了一个类似的问题:Do C# Timers elapse on a separate thread?
https://stackoverflow.com/questions/14920070
复制相似问题