Home > Software engineering >  Capture Countdown or Tick Event - Threading.Timer C#
Capture Countdown or Tick Event - Threading.Timer C#

Time:10-26

I have developed a program using Threading.Timer to call a method after 30 seconds.

The method is getting called, it's working but I want to get the event so that I can know how many seconds are left out of 30 sec.

I need a kind of tick event which gets fired every seconds. So that I can show the remaining seconds as well. This is my code:

Timer timerObj;

timerObj = new Timer(UpdateUI, null, Timeout.Infinite, Timeout.Infinite);
timerObj.Change(30000, Timeout.Infinite);


public void UpdateUI(object state)
{
    ShowQR= false;
}

How can I get countdown even ?

CodePudding user response:

This is how you'd go about implementing Evk's suggestion:

Timer timerObj;
Stopwatch stopwatch;

...

timerObj = new Timer(UpdateUI, null, Timeout.Infinite, Timeout.Infinite);
timerObj.Change(1000, Timeout.Infinite);
stopwatch = Stopwatch.StartNew();

public void UpdateUI(object state)
{
    if (stopwatch.Elapsed < TimeSpan.FromSeconds(30))
       {
         timerObj.Change(1000, Timeout.Infinite);
         return;
       }
        
    stopwatch.Restart();    
    ShowQR= false;
}

Note how you start the Stopwatch at the same time as you call timerObj.Change() to start the timer running.

Also note how the timer is set to fire every second rather than every 30s.

Then in the timer handler, you simply check the elapsed time on the Stopwatch - if it's less that 30s then just return; otherwise, do the thing you want to do every 30s and (IMPORTANT!) restart the Stopwatch.

  • Related