-2

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();
            }

        }
Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61
damu_d
  • 53
  • 1
  • 8
  • 2
    You should not be using `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 use `await Task.Delay(...)`. But that's unnecessary here. The whole point of a timer is to fire X often. – Zer0 Jan 24 '21 at 07:30
  • 1
    No need to sleep. The `Tick` is fired every `Interval` although note that accuracy may not be great so you may skip seconds – Charlieface Jan 24 '21 at 07:32
  • This seems to work correctly `code` //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 '21 at 13:17

1 Answers1

1

I'd use the DispatcherTimer for such a problem:

public float samplingTime = 1;

public MainWindow()
{
    dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
    dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
    dispatcherTimer.Interval = new TimeSpan(0,0,1);
    dispatcherTimer.Start();
}

private void dispatcherTimer_Tick(object sender, EventArgs e)
{
    tboxSampling.Text = DateTime.Now.AddSeconds(samplingTime).ToString();
}

Timers are not guaranteed to execute exactly when the time interval occurs, but they are guaranteed to not execute before the time interval occurs.

Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61