i want to segue to a new View Controller when the countdown timer, here set to 10 seconds, reaches 0 seconds. it does this using the thread logic below. the label usually shows the countdown "10, 9, 8, 7" but since i used ViewDidAppear, it doesnt show. at the end itll flash 0 seconds, and the segue will take place. i need the countdown to show the whole time, and cant figure out how and why its dissapearing
using System.Timers; using System.Threading;
... private System.Timers.Timer mytimer; private int countSeconds;
...
public override void ViewDidLoad()
{
base.ViewDidLoad();
mytimer = new System.Timers.Timer();
//Trigger event every second
mytimer.Interval = 1000; //1000 = 1 second
mytimer.Elapsed += OnTimedEvent;
countSeconds = 10; // 300 seconds
mytimer.Enabled = true;
mytimer.Start();
}
private void OnTimedEvent(object sender, ElapsedEventArgs e)
{
countSeconds--;
int seconds = countSeconds % 60;
int minutes = countSeconds / 60;
string DHCountdownTime = (countSeconds / 60).ToString() + ":" + (countSeconds % 60).ToString("00"); //to give leading 0. so 9 seconds isnt :9 but :09
InvokeOnMainThread(() =>
{
lblTimer.Text = DHCountdownTime;
});
if (countSeconds == 0)
{
mytimer.Stop();
}
}
...
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
Thread.Sleep(countSeconds * 1000);
PerformSegue("DHSegue", this);
...
Your Thread.Sleep
is blocking the UI thread:
Thread.Sleep(countSeconds * 1000);
Use a task (or another thread) in order allow the UI thread to continue to process messages:
await Task.Delay(countSeconds * 1000);