Home > other >  How to prevent my method launches every loop 10 seconds earlier
How to prevent my method launches every loop 10 seconds earlier

Time:11-25

I want my other method launches precice 1:50 (10 seconds before ending) The problem is, it launches 10secondes too early every loop. It looks like

     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)
      ......

I want every 110 seconds my method launches precisely every 110 seconds.

the code:

        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
                }
            });
        }

How to write it properly

CodePudding user response:

You could make a small change to the code.

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==============");
        }
    });
}

Hope it works for you.

  • Related