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

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

问题描述

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

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

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

我希望每 8 次旋转后延迟 1 秒.

i want 1 sec delay after each 8 rotation.

推荐答案

有很多方法可以做到:

  • 方法一:非常可怕:忙等待:

  • Method one: Criminally awful: Busy-wait:

DateTime timeToStartUpAgain = 随便;

while(DateTime.Now

这是一件可怕的事情;操作系统会假设您正在做有用的工作,并会分配一个 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 的缺点是目前仅处于测试阶段.

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天全站免登陆