damu_d
damu_d

Reputation: 53

Displaying next sampling time date and time without freezing WPF form in C#

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

        }

Upvotes: -2

Views: 168

Answers (1)

Athanasios Kataras
Athanasios Kataras

Reputation: 26450

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.

Upvotes: 1

Related Questions