在C#中使用计时器实现循环

时间:2013-07-02 06:29:19

标签: c# loops timer countdowntimer

我想在C#中使用基于定时器的while循环替换基于while循环的计数器。

示例:

while(count < 100000)
{
   //do something 
}

while(timer < X seconds)
{
    //do something 
}

对于此System.TimersThreading.Timers,我在C#.NET中有两种类型的计时器。 哪一个更好用,怎么样。我不想在计时器上增加额外的时间消耗或线程问题。

4 个答案:

答案 0 :(得分:17)

使用秒表课程怎么样。

using System.Diagnostics;
//...
Stopwatch timer = new Stopwatch();
timer.Start();
while(timer.Elapsed.TotalSeconds < Xseconds)
{
    // do something
}
timer.Stop();

答案 1 :(得分:7)

使用这样的结构:

Timer r = new System.Timers.Timer(timeout_in_ms);
r.Elapsed += new ElapsedEventHandler(timer_Elapsed);
r.Enabled = true;
running = true;
while (running) {
   // do stuff
}
r.Enabled = false;

void timer_Elapsed(object sender, ElapsedEventArgs e)
{
   running = false;
}

小心但是要在UI线程上执行此操作,因为它会阻止输入。

答案 2 :(得分:5)

您可以使用Stopwatch类代替它们,例如;

  

提供一组可用于的方法和属性   准确地测量经过的时间。

Stopwatch sw = new Stopwatch();
sw.Start();

while (sw.Elapsed < TimeSpan.FromSeconds(X seconds)) 
{
   //do something
}

来自TimeSpan.FromSecond

  

返回表示指定秒数的TimeSpan,   规范精确到最接近的毫秒。

答案 3 :(得分:1)

您也可以使用DateTime.Now.Ticks计数器:

long start = DateTime.Now.Ticks;
TimeSpan duration = TimeSpan.FromMilliseconds(1000);
do
{
  //
}
while (DateTime.Now.Ticks - start < duration);

然而,这似乎就像忙碌的等待。这意味着循环将导致CPU的一个核心以100%运行。它会减慢其他进程,加快粉丝a.s.o.虽然这取决于你打算做什么,但我建议在循环中加入Thread.Sleep(1)

相关问题