C#中System.Threading.Timer的一点使用注意事项

今天在使用 System.Threading.Timer的发现了一个问题,代码运行时间长了后 , timer执行的事件就没效果了。

把下面的代码,在开发windows service时,在OnStart方法中调用如下的Start方法,当服务启动完成后,系统对其中定义的对象进行回收【回收是不定时进行,所以可能会运行一段时间然后突然就不运行的情况发生】,这时候会把在 Start方法的timer进行回收,有可能会造成服务假死的情况.

代码如下:

 public static void Start() {
      System.Threading.Timer todo = new System.Threading.Timer(DoSomething, null, 0, 2000);
}
 public static void DoSomething(Object state) {
       Console.WriteLine($"{ DateTime.Now }");
       Console.WriteLine($"This Current Threading id is {Thread.CurrentThread.ManagedThreadId}");
       Console.WriteLine("*************************");
            
 }

后经过多方求证,原来是时间长了之后, 定义的  System.Threading.Timer todo 的被 GC 会回收掉了。

所以把 System.Threading.Timer todo要定义成全局变量,不给 GC回收的机会.

 static System.Threading.Timer todo;
 public static void Start() {
     todo = new System.Threading.Timer(DoSomething, null, 0, 2000);
}
 public static void DoSomething(Object state) {
            Console.WriteLine($"{ DateTime.Now }");
            Console.WriteLine($"This Current Threading id is {Thread.CurrentThread.ManagedThreadId}");
            Console.WriteLine("*************************");
            
        }

这样子,就能正常了。

猜测System.Timers.Timer t 这一个也应该有类似的注意点,但是暂时还没发现有这个坑,还需要进一步的验证。^_^^_^

原文地址:https://www.cnblogs.com/huaan011/p/14273468.html