C# timer (slowing down a loop)

后端 未结 4 2032
我寻月下人不归
我寻月下人不归 2020-12-19 02:58

I would like to slow down a loop so that it loops every 5 seconds.

In ActionScript, I would use a timer and a timer complete event to do this. How would I go about i

相关标签:
4条回答
  • 2020-12-19 03:34

    You can try using Timer,

    using System;
    
    public class PortChat
    {
        public static System.Timers.Timer _timer;
        public static void Main()
        {
    
            _timer = new System.Timers.Timer();
            _timer.Interval = 5000;
            _timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
            _timer.Enabled = true;
            Console.ReadKey();
        }
    
        static void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            //Do Your loop
        }
    }
    

    Also if your operation in loop can last more then 5 sec, You can set

     _timer.AutoReset = false;
    

    to disable next timer tick until operation finish in loop
    But then end end of loop You need again to enable timer like

     _timer.Enabled = true;
    
    0 讨论(0)
  • 2020-12-19 03:41

    You can add this call inside your loop:

    System.Threading.Thread.Sleep(5000); // 5,000 ms
    

    or preferable for better readability:

    System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));
    

    However, if your application has a user interface you should never sleep on the foreground thread (the thread that processes the applications message loop).

    0 讨论(0)
  • 2020-12-19 03:45

    Don't use a loop at all. Set up a Timer object and react to its fired event. Watch out, because these events will fire on a different thread (the timer's thread from the threadpool).

    0 讨论(0)
  • 2020-12-19 03:50

    Let's say you have a for-loop that you want to use for writing to a database every second. I would then create a timer that is set to a 1000 ms interval and then use the timer the same way you would use a while-loop if you want it to act like a for-loop. By creating the integer before the loop and adding to it inside it.

    public patial class Form1 : From
    {
        timer1.Start();
        int i = 0;
        int howeverLongYouWantTheLoopToLast = 10;
    
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (i < howeverLongYouWantTheLoopToLast)
            {
                writeQueryMethodThatIAssumeYouHave(APathMaybe, i); // <-- Just an example, write whatever you want to loop to do here.
                i++;
            }
            else
            {
                timer1.Stop();
                //Maybe add a little message here telling the user the write is done.
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题