Abdur Rahim Abdur Rahim - 27 days ago 4x
C# Question

Time delay in For loop in c#

how can i use a time delay in a loop after certain rotation?

for(int i = 0 ; i<64;i++)

i want 1 sec delay after each 8 rotation.


There are a lot of ways to do that:

  • Method one: Criminally awful: Busy-wait:

    DateTime timeToStartUpAgain = whatever;

    while(DateTime.Now < timeToStartUpAgain) {}

This is a horrible thing to do; the operating system will assume that you are doing useful work and will assign a CPU to do nothing other than spinning on this. Never do this unless you know that the spin will be only for a few microseconds. Basically when you do this you've hired someone to watch the clock for you; that's not economical.

  • Method two: Merely awful: Sleep the thread.

Sleeping a thread is also a horrible thing to do, but less horrible than heating up a CPU. Sleeping a thread tells the operating system "this thread of this application should stop responding to events for a while and do nothing". This is better than hiring someone to watch a clock for you; now you've hired someone to sleep for you.

  • Method three: Break up the work into smaller tasks. Create a timer. When you want a delay, instead of doing the next task, make a timer. When the timer fires its tick event, pick up the list of tasks where you left off.

This makes efficient use of resources; now you are hiring someone to cook eggs and while the eggs are cooking, they can be making toast.

However it is a pain to write your program so that it breaks up work into small tasks.

  • Method four: use C# 5's support for asynchronous programming; await the Delay task and let the C# compiler take care of restructuring your program to make it efficient.

The down side of that is of course C# 5 is only in beta right now.

NOTE: As of Visual Studio 2012 C# 5 is in use. If you are using VS 2012 or later async programming is available to you.