【问题标题】:Should I need to dispose System.Threading.Timer after completing my task?完成任务后是否需要处理 System.Threading.Timer?
【发布时间】:2019-06-18 08:56:39
【问题描述】:

我正在使用此代码在单独的线程上执行一次我的代码,延迟 10 秒。

System.Threading.Timer timer = null;
timer = new System.Threading.Timer(e=> {
    //My code
    timer.Dispose();
    },null,10000,System.Threading.Timeout.Infinite);  

我想问一下,完成任务后是否需要使用timer.Dispose(),否则定时器会自动释放。

【问题讨论】:

  • 根据this你应该。

标签: c# multithreading timer


【解决方案1】:

是的,您应该始终丢弃计时器。

来自docs

当不再需要定时器时,使用 Dispose 方法释放 计时器持有的资源。请注意,回调可能发生在 已调用 Dispose() 方法重载,因为计时器排队 由线程池线程执行的回调。您可以使用 Dispose(WaitHandle) 方法重载等到所有回调都有 完成。

【讨论】:

  • System.Timers.TimerSystem.Threading.Timer 不同。
  • 正确,刚刚更新了我的答案,但模式仍然适用。每次不需要时丢弃。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-26
  • 1970-01-01
  • 2010-11-07
  • 1970-01-01
  • 1970-01-01
  • 2012-10-09
相关资源
最近更新 更多