我想以200ms的间隔重复执行一些操作,从时间t = 0到t = 10秒。
目前,我正在跟踪变量中的已用时间。这对我来说很不舒服。以下是代码 -
using System;
using System.Timers;
class Program
{
static int interval = 200; // 0.2 seconds or 200 ms
static int totalTime = 10000; // 10 seconds or 10000 ms
static int elapsedTime = 0; // Elapsed time in ms
static Timer timer;
static void Main(string[] args)
{
timer = new Timer(interval);
timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
timer.Enabled = true;
Console.ReadKey(); // for checking
}
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
if (elapsedTime > totalTime)
timer.Stop();
else
{
// here I am performing the task, which starts at t=0 sec to t=10 sec
}
elapsedTime += interval;
}
}
请建议,如果有更好的方法来执行相同的任务。示例代码总是受到赞赏。
答案 0 :(得分:2)
您应该在活动中停止计时器并重新开始,只是为了确保您的执行没有两次进入该事件。像:
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
timer.Stop();
if (elapsedTime > totalTime)
{
return;
}
else
{
// here I am performing the task, which starts at t=0 sec to t=10 sec
timer.Enabled = true; //Or timer.Start();
}
elapsedTime += interval;
}