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

时间:2016-12-10 23:11:57

标签: c#

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

2 个答案:

答案 0 :(得分:17)

您可以在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));
    }

请确保您的计时器不会超出范围并被处置。

答案 1 :(得分:2)

就像这样,你定义一个静态的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
     }
    }