How to implement setInterval(js) in C#

前端 未结 2 1466
误落风尘
误落风尘 2021-02-19 19:54

JS\'s setInterval and setTimeOut is really convenient. And I want to ask how to implement the same thing in C#.

2条回答
  •  没有蜡笔的小新
    2021-02-19 20:33

    Its simply like this, you define an static System.Timers.Timer; then call the function that binds the timer.Elapsed event to your interval function that will be called each X miliseconds.

       public class StaticCache {        
          private static System.Timers.Timer syncTimer;
    
          StaticCache(){
            SetSyncTimer();
          }
          private void SetSyncTimer(){
            // Create a timer with a five second interval.
            syncTimer = new System.Timers.Timer(5000);
    
            // Hook up the Elapsed event for the timer. 
            syncTimer.Elapsed += SynchronizeCache;
            syncTimer.AutoReset = true;
            syncTimer.Enabled = true;
         }
         private static void SynchronizeCache(Object source, ElapsedEventArgs e)
         {
            // do this stuff each 5 seconds
         }
        }
    

提交回复
热议问题