tags:

views:

135

answers:

3

Hi I am a newbee to c# so please forgive me. I would like to slow down a loop so that it loops every 5 seconds. In actionscript I would use a timer and timer complete event to do this. How would I go about it in c#? Any pointers appreciated

+5  A: 

You can add this call inside your loop:

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

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

Martin Liversage
Worked a treat thanks!
Chin
This code will wait 5 seconds between each iteration, not fire each 5 second. If the code you are doing in your loop takes long time, like a web request, then total will be longer than 5 seconds. The solution with a Timer from adopilot is more accurate to your question, but any solution may be suitable to your needs.
Albin Sunnanbo
For readability the Sleep function also can take an TimeSpan as an argument.System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));
Albin Sunnanbo
+4  A: 

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;
adopilot
+1  A: 

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

Neil Barnwell