A
A
Andrew2015-08-23 14:09:07
WPF
Andrew, 2015-08-23 14:09:07

How to make a timer counting from 4 to 0 and loop?

Tell me how to make the value decrease from four to zero, then again from 4 to 0 and so on. I'm not very good at

public MainWindow()
        {
            InitializeComponent();

            System.Timers.Timer _timer = new System.Timers.Timer();
            _timer.Elapsed += Timer_Elapsed;
            _timer.Interval = 1;
            _timer.Start();
        }

        int b = 4;
        
        void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (b <= 4)
            {
                b--;
                label1.Content = b;
            }

            if (b <= 0)
            {
                b = 4;
                label1.Content = b;
            }
        }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Oscar S, 2015-08-23
@Kaspel

Use DispatcherTimer . And there will be happiness (:

public MainWindow()
        {
            InitializeComponent();

            int b = 0;
            var uiTimer = new System.Windows.Threading.DispatcherTimer();
            uiTimer.Tick += (sender, e) => {
                label1.Content = b = b == 0 ? 4 : --b;
            };
            uiTimer.Interval = TimeSpan.FromSeconds(1);
            
            uiTimer.Start();
        }

M
MrDywar Pichugin, 2015-08-23
@Dywar

if ( b <= 0 )
            {
                Console.WriteLine( b );
                b = 4;
            }

            if ( b <= 4 )
            {
                Console.WriteLine( b );
                b--;
            }

UPD:
I understand what your problem is. In thread synchronization.
1) You can use the Timer class from the System.Windows.Forms namespace. Instantiating this class tells Windows to associate the timer with the calling thread. Your code will work as you expected it to before.
2) Use synchronization context transfer.
3) Use the InvokeRequired method on the control (there are actions similar to paragraph 2). Example:
if ( this.Control.InvokeRequired )
{
   this.Control.Invoke( new Action( () =>
   {
      this.Control.AppendText( message );
   } ) );
}
else
{
   this.Control.AppendText( message );
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question