1

I am trying to get the data from a 'DatePicker' called targetDate and a couple of 'TextBox' called targetHour and targetMinute. I want to read whatever is in them every second. So I created a timer as follows:

System.Timers.Timer tmr = null;
private void SetTimer()
{
    tmr = new System.Timers.Timer(1000);
    tmr.AutoReset = true;
    tmr.Elapsed += TimerEvent;
    tmr.Enabled = true;
}

The timer is running fine and I am getting the data as well. For now, just for verification purposes I am displaying whatever I get from the targetDate, targetHour and targetMinute to another TextBox differenceTime inside the TimerEvent.

Dispatcher.BeginInvoke(new ThreadStart(() => targetDT = targetDate.Text));
Dispatcher.BeginInvoke(new ThreadStart(() => targethh = Int32.Parse(targetHour.Text)));
Dispatcher.BeginInvoke(new ThreadStart(() => targetmm = Int32.Parse(targetMinute.Text)));
//temp = targetDT + " " + targethh + ":" + targetMinute;
Dispatcher.BeginInvoke(new ThreadStart(() => differenceTime.Text = targetDT + "-" + targethh));

The above code is working ok. My main question is, is there a better way to do this, without using the Dispatcher.BeginInvoke? Also, but less important, if I try to use the temp string to populate differenceTime it doesn't work, why is that?

Newton
  • 408
  • 1
  • 9
  • 18

2 Answers2

1

My main question is, is there a better way to do this, without using the Dispatcher.BeginInvoke?

Either replace the System.Timers.Timer with a DispatcherTimer as suggested by @Jeff R and handle its Tick event. Then the code inside your Tick event handler will always be executed on the UI thread which means that you can access the controls directly.

You could also improve your current code by only calling Dispatcher.BeginInvoke once:

Dispatcher.BeginInvoke(new Action(() =>
{
    targetDT = targetDate.Text;
    targethh = Int32.Parse(targetHour.Text);
    targetmm = Int32.Parse(targetMinute.Text);
    differenceTime.Text = targetDT + "-" + targethh;
}));

Also, but less important, if I try to use the temp string to populate differenceTime it doesn't work, why is that?

Because Dispatcher.BeginInvoke returns before the delegate that you pass to it has been executed on the UI thread. You probably want to use Dispatcher.Invoke instead.

What's the difference between Invoke() and BeginInvoke()

mm8
  • 135,298
  • 10
  • 37
  • 59
0

You are using WPF correct?

Then try using a System.Windows.Timer.DispatcherTimer instead of the System.Timers.Timer. The DispatcherTimer will run on the UI thread so may not be as accurate to the ms but won't require all the BeginInvoke calls.

Jeff R.
  • 1,310
  • 1
  • 8
  • 12