Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
963 views
in Technique[技术] by (71.8m points)

timer - Time delay in For loop in c#

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

for(int i = 0 ; i<64;i++)
{
........
}

i want 1 sec delay after each 8 rotation.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...