所以我知道是因为问题 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/