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 這一個也應該有類似的注意點,但是暫時還沒發現有這個坑,還需要進一步的驗證。^_^^_^


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM