0

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?

1
  • Hey , i need to do this too. How did u do it without sleep Commented Mar 21, 2015 at 11:48

5 Answers 5

10

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

Sign up to request clarification or add additional context in comments.

1 Comment

I would even suggest it's worth mentioning setTimeout() in Javascript to give him something to search for.
3

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.

Comments

2

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.

Comments

0

you can use Thread.Sleep();

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

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

Comments

-1

How about something like

System.Threading.Thread.Sleep(1000);

Thread.Sleep Method (Int32)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.