Dharmik Bhandari
Dharmik Bhandari

Reputation: 1702

How to add some delay between each iteration of for loop in C#?

I'm working on ASP.NET MVC3 with C#. I want to add some delay between each iteration of for loop.

for(int i=0; i<5; i++)
{
    //some code
    //add delay here
}

So How can I do this?

Upvotes: 0

Views: 14288

Answers (5)

Ronald Wildenberg
Ronald Wildenberg

Reputation: 32144

Another approach then the ones already described may be Reactive Extensions (Rx). There are some methods in there that generate sequences of values in time. In your case, you could use the following code.

var values = Observable.Generate(
        0,           // Initializer.
        i => i < 5,  // Condition.
        i => i + 1,  // Iteration.
        i => i,      // Result selector.
        i => TimeSpan.FromSeconds(1));
var task = values
    .Do(i => { /* Perform action every second. */ })
    .ToTask();
values.Wait();

The ToTask call allows you to wait for the IObservable to complete. If you don't need this, you can just leave it out. Observable.Generate generates a sequence of values at specific timestamps.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1504122

As other answers have said, using Thread.Sleep will make a thread sleep... but given that you're writing a web app, I don't think it'll do what you want it to.

If the aim is for users to see things happening one second at a time, you'll need to put the delay on the client side. If you have five one-second delays before you send an HTTP response, that just means the user will have to wait five seconds before they see your result page.

It sounds like you should be doing this with AJAX.

EDIT: As noted in comments, it's probably worth you looking at the window.setTimeout Javascript call. (I don't "do" Javascript, so I'm afraid I won't be able to help with any of the details around that.)

Upvotes: 10

nunespascal
nunespascal

Reputation: 17724

The simplest way is to put the current thread to sleep.

System.Threading.Thread.Sleep (200);

Remember though, that threads in a web application are very precious resources, and putting one to sleep still keeps the thread busy.

There is usually no good reason to do this in a web application.
Whatever problem needs you to do this, can be solved in a better manner.

Upvotes: 3

Ajeet Pratap Maurya
Ajeet Pratap Maurya

Reputation: 4254

you can use Thread.Sleep();

int milliseconds = 5000;
Thread.Sleep(milliseconds);

this stops the execution of the current thread for 5 seconds.

Upvotes: 0

Adriaan Stander
Adriaan Stander

Reputation: 166626

How about something like

System.Threading.Thread.Sleep(1000);

Thread.Sleep Method (Int32)

Upvotes: -1

Related Questions