How can I write a code to make a delay at the end of my “for loop” to make e.g. 1 millisecond delay before going through the next loop?
Asked
Active
Viewed 4,750 times
0
-
2I don't think you can add a delay of 1 ms accurately , you may see this similar question for adding delay http://stackoverflow.com/questions/5449956/how-to-add-a-delay-for-a-2-3-seconds?answertab=votes#tab-top – Habib Feb 24 '14 at 16:53
-
For such a small time delay (1ms) I'd probably use a spinner in conjunction with a `Stopwatch`. – Nick Gotch Feb 24 '14 at 19:03
4 Answers
5
Thread.Sleep(1)
will wait for at least 1 millisecond. More realistically it will sleep for about 16ms, as it gives up your thread's time slice and something else will get to run for a full time slice before it can resume.

Cory Nelson
- 29,236
- 5
- 72
- 110
1
Try using Thread.Sleep(1)
The input parameter for Thread.Sleep is the millisecond delay you want.

steinmas
- 398
- 3
- 9
0
You can use
Try{
Thread.Sleep(1);
}Catch(Exception e){
}

Ashish Ratan
- 2,838
- 1
- 24
- 50
-
Why the try catch call? Can a Thread.Sleep() call cause an exception on its own? – Chris Schiffhauer Feb 24 '14 at 17:03
-
1
-
i can't use thread as it will terminate the whole programme. but i just need to put delay in part of my programme. how can i make a delay function plz? – CowBoy Feb 24 '14 at 17:06
-
why ? i mean why it will terminate the whole code? if u'll handle it in catch clause it will work smoothely.. – Ashish Ratan Feb 24 '14 at 17:09
-
another way, u can also use a free for loop till 1000 steps before executing your second loop – Ashish Ratan Feb 24 '14 at 17:12
-
0
If you need to avoid the Thread class, and are using .NET 4.5 asynchronously, you can use the following:
await Task.Delay(1);

Chris Schiffhauer
- 17,102
- 15
- 79
- 88