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 dela
You can use something like a one-second delay:
System.Threading.Thread.Sleep (1000);
though make sure this is only for debugging purposes. There's little more annoying than intentionally slowing down software.
Other than an easy way to introduce performance improvements later, of course :-)
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.
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.
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.)
you can use Thread.Sleep();
int milliseconds = 5000;
Thread.Sleep(milliseconds);
this stops the execution of the current thread for 5 seconds.
How about something like
System.Threading.Thread.Sleep(1000);
Thread.Sleep Method (Int32)