I am writing a code in WPF & C# to display next sampling time in Date and time format. For example, if sampling time is one minute and current time is 08:00 - the next sampling time should show 08:01, Next sampling time is displayed once 08:01 has passed.
I have tried using dispatcherTimer and sleep thread. But when I use the whole WPF form freezes until next update.
Could you please help me?
code ->
public float samplingTime = 1;
public MainWindow()
{
InitializeComponent();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += timer_Tick;
timer.Start();
tboxSampling.Text = DateTime.Now.AddSeconds(samplingTime).ToString();
void timer_Tick(object sender, EventArgs e)
{
System.Threading.Thread.Sleep((int)samplingTime*1000);
tboxSampling.Text = DateTime.Now.AddSeconds(samplingTime).ToString();
}
}
Thread.Sleep
at all. Simply modify your timer interval or skip timer ticks. If you want to wait without blocking the thread you could also useawait Task.Delay(...)
. But that's unnecessary here. The whole point of a timer is to fire X often. – Zer0 Jan 24 at 7:30Tick
is fired everyInterval
although note that accuracy may not be great so you may skip seconds – Charlieface Jan 24 at 7:32code
//timer to display sampling time in time window tboxSampling.Text = DateTime.Now.AddSeconds(samplingTime).ToString(); timer.Interval = TimeSpan.FromSeconds(samplingTime); timer.Tick += timer_Tick; timer.Start(); void timer_Tick(object sender, EventArgs e) { dtEnd = DateTime.Now.AddSeconds(samplingTime); tboxSampling.Text = dtEnd.ToString(); running = true; } – damu_d Jan 24 at 13:17