我想每隔200毫秒重复执行某个操作,从时间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;
}
}
请您建议是否有更好的方法来执行相同的任务。欢迎提供示例代码。