Thread.Sleep
will cause the UI thread to sleep for 1 second. The UI will not update until your method returns.
Try using an
async
method instead:
private void btnStartTimer_Click(object sender, EventArgs e)
{
int minutes, seconds;
if (!int.TryParse(txtMinutes.Text, out minutes))
{
txtMinutes.Focus();
return;
}
if (!int.TryParse(txtSeconds.Text, out seconds))
{
txtSeconds.Focus();
return;
}
var time = new TimeSpan(0, minutes, seconds);
_ = RunTimer(time);
}
private async Task RunTimer(TimeSpan time)
{
btnStartTimer.Enabled = false;
txtMinutes.ReadOnly = true;
txtSeconds.ReadOnly = true;
try
{
TimeSpan tick = TimeSpan.FromSeconds(1);
while (time > TimeSpan.Zero)
{
txtMinutes.Text = Convert.ToString((int)Math.Floor(time.TotalMinutes));
txtSeconds.Text = time.Seconds.ToString();
await Task.Delay(tick);
time -= tick;
}
}
finally
{
btnStartTimer.Enabled = true;
txtMinutes.ReadOnly = false;
txtSeconds.ReadOnly = false;
}
}