如何在C#中实现setInterval(js)

JS的setInterval和setTimeOut非常方便。 我想问一下如何在C#中实现相同的function。

您可以在Task.Delay中执行Task.Run ,尝试:

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

然后你甚至可以将它包装到你自己的SetInterval方法中,该方法接受一个动作

 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); } } 

或者你可以使用内置的Timer类,它实际上做同样的事情

  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)); } 

只要确保你的定时器不会超出范围并被处理掉。

它就像这样,你定义一个静态的System.Timers.Timer; 然后调用将timer.Elapsed事件绑定到interval函数的函数,该函数将在每X毫秒调用一次。

  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 } }