首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >启用System.Timers.Timer和GarbageCollector

启用System.Timers.Timer和GarbageCollector
EN

Stack Overflow用户
提问于 2013-02-17 18:21:11
回答 2查看 878关注 0票数 2

在我的项目中,我创建了System.Timers.Timer对象,间隔设置为10分钟。每10分钟,我就会得到一个流逝的事件。在这个事件处理程序中,我正在执行一些代码。

在执行这段代码之前,我将Enabled属性设置为false,因为如果处理程序的执行时间比下一个时间间隔长,则另一个线程将执行elapsed事件。

这里的问题是Elapsed事件突然停止。

我读过一些文章,怀疑moment enabled属性设置为false garbagecollector会释放timer对象。

如果是正确的,请告诉我解决方案。

以下是示例代码:

代码语言:javascript
复制
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;
    }
}
EN

回答 2

Stack Overflow用户

发布于 2013-02-17 18:29:50

由于您的类中有一个字段指向timer对象,因此GC不会收集timer对象。

但是您的代码可能会引发异常,这可能会阻止Enabled属性再次变为true。为了防止这一点,你应该使用一个finally块:

代码语言:javascript
复制
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;
    }
}
票数 3
EN

Stack Overflow用户

发布于 2013-02-17 18:31:18

您可以设置同步对象,在这种情况下,流逝将只发生在该对象的所有者线程上,不具有并发性。这里发布了一个类似的问题:Do C# Timers elapse on a separate thread?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14920070

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档