实现使用C#计时器的循环 [英] Implementing a loop using a timer in C#
本文介绍了实现使用C#计时器的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想基础,同时更换计数器循环与基于定时器while循环C#
I wanted to replace a counter based while loop with the timer based while loop in C#.
例如:
while(count < 100000)
{
//do something
}
到
while(timer < X seconds)
{
//do something
}
我有两种类型在C#.NET定时器本的 System.Timers
和 Threading.Timers
。
哪一个会更好使用,how.I不想增加额外的时间消耗或计时器线程问题。
I have two types of timers in C# .NET for this System.Timers
and 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.
推荐答案
使用一个结构是这样的:
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;
}
不过要小心这样做的UI线程上,因为它会阻止输入
Be careful though to do this on the UI thread, as it will block input.
这篇关于实现使用C#计时器的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文