I added a timer to the form1 designer.
In the top of form1:
private int countdownSeconds = 300; // 5 minutes
private Stopwatch stopwatch = new Stopwatch();
form1 constructor:
public Form1()
{
InitializeComponent();
timer1.Interval = 100; // Update every 100 milliseconds
StartTimer();
DownloadFolderViewerButtonStates();
ResetUI();
graphicsDrawer = new GraphicsDrawer();
startTime = DateTime.Now;
}
the method StartTimer:
private void StartTimer()
{
countdownSeconds = 300; // Reset the countdown time
stopwatch.Restart();
timer1.Start();
}
the timer tick event:
private async void timer1_Tick(object sender, EventArgs e)
{
countdownSeconds -= 100; // Subtract the timer interval (100 milliseconds) from the countdown
if (countdownSeconds <= 0)
{
timer1.Stop();
radar = new Radar(downloadFolder);
await radar.PrepareLinksAsync(); // Use await here
DownloadFiles(radar.links);
StartTimer(); // Restart the timer after the download is complete
}
TimeSpan remainingTime = TimeSpan.FromMilliseconds(countdownSeconds);
// Display time with milliseconds
lblTimer.Text = $"{remainingTime.Hours:D2}:{remainingTime.Minutes:D2}:{remainingTime.Seconds:D2}:{(int)remainingTime.TotalMilliseconds:D3}";
}
The problem is that on the milliseconds I see 3 digits like 000 and the digits change between 1 and 3 on the first zero digit like: 100 then "jump" to 300 or to 200 and so on between 1 and 3 on the last digits.
the minutes and seconds stay on 00:00
but I want it to be like a timer that count down 5 minutes including milliseconds , seconds , and minutes.
>Solution :
Your error is not minding your units.
In one place countdownSeconds is set to 300 seconds. But in the timer tick event handler – for some odd reason – you treat that number as milliseconds. Resulting in
a roll-over every 300 millis.
And then you parse those into a TimeSpan FromMilliseconds. So all you will ever see is 300ms, 200ms, 100ms and 0.
Now that we have identified the error, I’d suggest you don’t do it like this at all.
Set a target timestamp ( e.g. "now" + 5 mins ) and in the tick handler, update via ‘target – now’. To reset, set the target again to ‘now + 5 mins’.