C#定时器(减慢循环)
我想减慢一个循环,使其每5秒循环一次。
在ActionScript中 ,我将使用计时器和计时器完成事件来执行此操作。 我将如何在C#中解决这个问题?
您可以在循环中添加此调用:
System.Threading.Thread.Sleep(5000); // 5,000 ms
或者更好的可读性:
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));
但是,如果您的应用程序具有用户界面,则不应该在前台线程(处理应用程序消息循环的线程)上hibernate。
您可以尝试使用Timer,
using System; public class PortChat { public static System.Timers.Timer _timer; public static void Main() { _timer = new System.Timers.Timer(); _timer.Interval = 5000; _timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed); _timer.Enabled = true; Console.ReadKey(); } static void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { //Do Your loop } }
此外,如果你的循环操作持续时间超过5秒,你可以设置
_timer.AutoReset = false;
禁用下一个计时器滴答,直到操作完成循环
但是然后结束循环你需要再次启用计时器
_timer.Enabled = true;
根本不要使用循环。 设置Timer
对象并对其触发的事件做出反应。 注意,因为这些事件将在另一个线程(来自线程池的计时器线程)上触发。
假设你有一个for
-loop,你想用它来每秒写入一个数据库。 然后我会创建一个设置为1000毫秒间隔的计时器,然后像使用while
-loop一样使用计时器,如果你想让它像for
-loop一样工作。 通过在循环之前创建整数并在其中添加它。
public patial class Form1 : From { timer1.Start(); int i = 0; int howeverLongYouWantTheLoopToLast = 10; private void timer1_Tick(object sender, EventArgs e) { if (i < howeverLongYouWantTheLoopToLast) { writeQueryMethodThatIAssumeYouHave(APathMaybe, i); // <-- Just an example, write whatever you want to loop to do here. i++; } else { timer1.Stop(); //Maybe add a little message here telling the user the write is done. } } }