How to implement setInterval(js) in C#

前端 未结 2 1292
误落风尘
误落风尘 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:26

    You can just do a Task.Delay within a Task.Run, try out:

    var task = Task.Run(async () => {
                            for(;;)
                            {
                                await Task.Delay(10000)
                                Console.WriteLine("Hello World after 10 seconds")
                            }
                        });
    

    Then You could even wrap this up in to your own SetInterval method that takes in an action

    class Program
    {
        static void Main(string[] args)
        {
            SetInterval(() => Console.WriteLine("Hello World"), TimeSpan.FromSeconds(2));
            SetInterval(() => Console.WriteLine("Hello Stackoverflow"), TimeSpan.FromSeconds(4));
    
    
            Thread.Sleep(TimeSpan.FromMinutes(1));
        }
    
        public static async Task SetInterval(Action action, TimeSpan timeout)
        {
            await Task.Delay(timeout).ConfigureAwait(false);
    
            action();
    
            SetInterval(action, timeout);
        }
    }
    

    or you could just use the built in Timer class which practically does the same thing

        static void Main(string[] args)
        {
    
            var timer1 = new Timer(_ => Console.WriteLine("Hello World"), null, 0, 2000);
            var timer2 = new Timer(_ => Console.WriteLine("Hello Stackoverflow"), null, 0, 4000);
    
    
            Thread.Sleep(TimeSpan.FromMinutes(1));
        }
    

    Just make sure you're timers don't go out of scope and get disposed.

    0 讨论(0)
  • 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
         }
        }
    
    0 讨论(0)
提交回复
热议问题