C#中For循环的时间延迟 [英] Time delay in For loop in c#

查看:246
本文介绍了C#中For循环的时间延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在特定旋转后如何在循环中使用时间延迟?
假设:

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

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

我希望延迟1秒每8圈。

i want 1 sec delay after each 8 rotation.

推荐答案

有很多方法可以做到:


  • 方法一:犯罪可怕:繁忙等待:

  • Method one: Criminally awful: Busy-wait:

DateTime timeToStartUpAgain =什么;

while(DateTime.Now< timeToStartUpAgain){}

这是一件可怕的事情;操作系统将假定您正在做有用的工作,并且将分配CPU来执行此操作。除非您知道旋转只会持续几微秒,否则不要执行 。基本上,当您这样做时,您已经雇用了某人为您计时。

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.


  • 方法二:太糟糕了:休眠线程。

休眠线程也是一件可怕的事情,但没有比加热CPU可怕的了。休眠线程会告诉操作系统此应用程序的此线程应暂时停止响应事件,并且不执行任何操作。这比雇用某人为您看时钟要好。现在您已经雇用了某人为您睡觉。

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.


  • 方法三:将工作分解为较小的任务。创建一个计时器。当您需要延迟时,而不是执行下一个任务,请创建一个计时器。当计时器触发其滴答事件时,从上次中断的任务列表中选取。

这可以有效利用资源;现在您正在雇用某人来煮鸡蛋,并且在煮鸡蛋的同时,它们还可以烤面包。

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.


  • 方法四:使用C#5对异步编程的支持; 等待Delay任务,然后让C#编译器负责重组程序以使其高效。

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

不利的一面当然是C#5目前仅在beta中。

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

注意:从Visual Studio 2012开始,C#5已在使用中。如果您使用的是VS 2012或更高版本,则可以使用异步编程。

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.

这篇关于C#中For循环的时间延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆