How to implement setInterval(js) in C#

前端 未结 2 1320
误落风尘
误落风尘 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.

提交回复
热议问题