Chin
Chin

Reputation: 12712

C# timer (slowing down a loop)

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 it in C#?

Upvotes: 9

Views: 22437

Answers (4)

Charp
Charp

Reputation: 198

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

Upvotes: 1

Neil Barnwell
Neil Barnwell

Reputation: 42175

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).

Upvotes: 4

Martin Liversage
Martin Liversage

Reputation: 106956

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).

Upvotes: 18

adopilot
adopilot

Reputation: 4520

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;

Upvotes: 11

Related Questions