我想以 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;
}
}
如果有更好的方法来执行相同的任务,请提出建议。示例代码总是受到赞赏。
最佳答案
您应该停止事件中的计时器并重新开始,以确保您的执行不会两次进入事件。喜欢:
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;
}
关于c# - 在 C# 中一段时间后停止计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23500442/