在 C# 中使用计时器实现循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17418820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Implementing a loop using a timer in C#
提问by Raulp
I wanted to replace a counter based while loop with the timer based while loop in C#.
我想用 C# 中基于计时器的 while 循环替换基于计数器的 while 循环。
Example :
例子 :
while(count < 100000)
{
//do something
}
to
到
while(timer < X seconds)
{
//do something
}
I have two types of timers in C# .NET for this System.Timersand Threading.Timers.
Which one will be better to use and how.I don't want to add extra time consumption or threading issues with the timer.
我在 C# .NET 中有两种类型的计时器用于此System.Timers和Threading.Timers. 哪个更好用以及如何使用。我不想增加额外的时间消耗或计时器的线程问题。
采纳答案by Bart Friederichs
Use a construct like this:
使用这样的构造:
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;
}
Be careful though to do this on the UI thread, as it will block input.
在 UI 线程上执行此操作时要小心,因为它会阻止输入。
回答by Casperah
What about using the Stopwatch class.
使用秒表类怎么样。
using System.Diagnostics;
//...
Stopwatch timer = new Stopwatch();
timer.Start();
while(timer.Elapsed.TotalSeconds < Xseconds)
{
// do something
}
timer.Stop();
回答by Soner G?nül
You can use Stopwatchclass instead of them, like;
您可以使用Stopwatchclass 代替它们,例如;
Provides a set of methods and properties that you can use to accurately measure elapsed time.
提供一组可用于准确测量经过时间的方法和属性。
Stopwatch sw = new Stopwatch();
sw.Start();
while (sw.Elapsed < TimeSpan.FromSeconds(X seconds))
{
//do something
}
From TimeSpan.FromSecond
Returns a TimeSpan that represents a specified number of seconds, where the specification is accurate to the nearest millisecond.
返回表示指定秒数的 TimeSpan,其中指定精确到最接近的毫秒。
回答by JeffRSon
You might as well use the DateTime.Now.Tickscounter:
您不妨使用DateTime.Now.Ticks计数器:
long start = DateTime.Now.Ticks;
TimeSpan duration = TimeSpan.FromMilliseconds(1000);
do
{
//
}
while (DateTime.Now.Ticks - start < duration);
However, this seems to be something like busy waiting. That means that the loop will cause one core of your CPU to run at 100%. It will slow down other processes, speed up fans a.s.o. Although it depends on what you intend to do I would recommend to include Thread.Sleep(1)in the loop.
然而,这似乎是一种忙碌的等待。这意味着循环将导致 CPU 的一个核心以 100% 的速度运行。它会减慢其他进程,加快风扇速度虽然这取决于您打算做什么,但我建议将其包含Thread.Sleep(1)在循环中。

