如何防止我的方法提前10秒启动每个循环



我希望我的另一个方法启动精确1:50(结束前10秒)问题是,它启动太早10秒每个循环。它看起来像

1 st loop
1:50  Method launches - correct
2 nd loop 
3:40  Method launches - incorrect (10 seconds shorter)
3 rd loop 
5:30  Method launches - incorrect (10 seconds shorter)
4 th loop 
7:20  Method launches - incorrect (10 seconds shorter)
......

我想要每110秒我的方法精确地每110秒启动一次。

代码:

private void OnTimerElapsed(object sender, ElapsedEventArgs e)
{
Application.Current.Dispatcher.BeginInvokeOnMainThread(() =>
{
MainTimer.Text = stopwatch.Elapsed.ToString(@"hh:mm:ss");
double counter = stopwatch.Elapsed.TotalSeconds;
Tasklabel.Text = counter.ToString(); // tried to look what's going on
if (((int)counter % 120 == 0 && (int)counter != 0))
{
Value = false;
stopwatch.Stop();
timer.Stop();
// do sth
}
// I tried
//counter2 += 10; 
// also tried to assign another variable // double counter2 = stopwatch.Elapsed.TotalSeconds;
if (((int)counter2 % 110 == 0 && (int)counter2 != 0))
{
// do sth
}
});
}

如何正确书写

您可以对代码做一些小改动。

private void OnTimerElapsed(object sender, ElapsedEventArgs e)
{
Application.Current.Dispatcher.BeginInvokeOnMainThread(() =>
{
MainTimer.Text = stopwatch.Elapsed.ToString(@"hh:mm:ss");
double counter = stopwatch.Elapsed.TotalSeconds;
if ((((int)counter + 10) % 120 == 0 && (int)counter != 0)) // make changes here
{
//make a stop at 1:50, 3:50, 5:50...
Value = false;
timer.Stop();
stopwatch.Stop();
counter = 0;
// do sth
Console.WriteLine("TIMER Close==============");
}
});
}

希望它对你有用。

最新更新