c# - 我必须停止 System.Timers.Timer 吗?

标签 c# timer garbage-collection

所以我知道是因为问题 Can Timers get automatically garbage collected? System.Timers.Timer 一开始就不会被垃圾回收。

但我的实际问题是 - 我是否必须停止或处理 Timer?

private void CreateTimer()
{
    var timer = new Timer();
    timer.Elapsed += TimerElapsed;
    timer.Interval = 30000;
    timer.AutoReset = true;
    timer.Enabled = true;
}

我的意思是这个计时器将永远运行。但是现在我不再需要在方法中创建计时器的对象了。我是否必须停止或处置它收集垃圾的 Timer

最佳答案

我认为在您调用 .Dispose() 之前它不会被垃圾回收在上面。不管你是.Stop()定时器。

所以看起来调用 Timer.Stop()或设置 Timer.Enabled到 false 就足够了,因为那会调用 Timer.Dispose()为你。 引用:Timer.Enabled

来自 MSDN:

Always call Dispose before you release your last reference to the Component. Otherwise, the resources it is using will not be freed until the garbage collector calls the Component object's Finalize method. More here

如果您希望它被自动处理掉,那么使用 Timer.Elapsed 将该逻辑放在一个单独的方法中属性(property)说明Here .

关于c# - 我必须停止 System.Timers.Timer 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46405440/

相关文章:

c# - 具有变化属性的对象的可观察列表

c# - 与 IndexOutOfRangeException 相关的问题

c# - 数组中的一个或两个 JSON 反序列化

javascript - Node.JS 定时器中断

windows - 在定义的时间内等待窗口消息

c - C中的计时器实现,用于在计时器到期后删除链表中的记录

performance - Java 7 与 Java 5 垃圾收集

java - JVM CMS 垃圾收集问题

c# - XML读取子节点

c# - 为什么 IntPtr 不需要 unsafe 关键字?