c#每10秒执行一次if语句



我希望我的代码(messagebox)在这个循环计时器中运行不早于10秒,这是2000毫秒。这可能吗?我希望if语句每10秒或更长时间执行一次,而不是更少,即使循环是2秒。

public void InitBrowser()
{
Timer t = new Timer();
t.Interval = 2000;
t.Tick += new EventHandler(timer_Tick);
t.Start();
}
void timer_Tick(object sender, EventArgs e)
{
mycode();
}
public async void mycode()
{
DateTime SOMETIME = DateTime.Today;
if (DateTime.Now.Subtract(SOMETIME).TotalSeconds > 10)
{
MessageBox.Show("RUNNED");
}
}

正如在注释中提到的,最干净的方法是使用每10秒滴答一次的计时器,即使这意味着必须创建一个与其他代码使用的计时器分开的计时器。

如果你绝对必须这样做,然而,你需要保持状态(即一个实例字段),它可以跟踪你最后一次运行代码的时间,或者你应该下次运行它的时间,或者自从你运行它已经多久了。如果你想继续使用DateTime,你应该使用DateTime.UtcNow而不是DateTime.Now,否则你很可能会在夏令时边界附近遇到问题。即使使用DateTime.UtcNow,您也可能因为系统时钟更新而出现问题—使用Stopwatch来跟踪自上次运行以来经过的时间可能是更好的选择。所以代码看起来像这样:

public class WhateverYourClassIsCalled
{
private static readonly TimeSpan ExecutionInterval = TimeSpan.FromSeconds(10);
// TODO: Rename to something more meaningful (we don't know what the code does)
private readonly Stopwatch stopwatch;
public void InitBrowser()
{
stopwatch = Stopwatch.StartNew();
Timer t = new Timer { Interval = 2000 };
t.Tick += (sender, args) => HandleTimerTick();
t.Start();
}
// TODO: Avoid async void if possible
private async void HandleTimerTick()
{
if (stopwatch.Elapsed >= ExecutionInterval)
{
stopwatch.Restart();
// Execute your code here
}
// Other code here
}
}

最新更新