Reputation: 519
I have a WPF app with a textblock that displays the current time. Said textblock is bound to a DependencyProperty on the ViewModel. Naturally I need to keep updating the time, so I used a timer (System.Threading.Timer) like so:
public MainViewModel()
{
_dateTimer = new Timer(_dateTimer_Tick, null, 0, 60000);
}
void _dateTimer_Tick(object sender)
{
Time = DateTime.Now.ToString("HH:mm");
Date = DateTime.Now.ToString("D");
}
The thing is, when the callback is called, the app exits... bummer (output says: "A first chance exception of type 'System.InvalidOperationException' occurred in WindowsBase.dll" just when it's about to write to the Time DP).
If I use a DispatcherTimer everything works fine. I don't mind using a DispatcherTimer, it's just that the app is quite big and I wanted to tweak out its performance the best I could. As far as I can see I'm not accessing the UI thread (I'm just updating a property) so a DispatcherTimer wouldn't be needed.
Am I missing something?
Thanks.
EDIT: The properties are defined like this:
public string Time
{
get { return (string)GetValue(TimeProperty); }
set { SetValue(TimeProperty, value); }
}
// Using a DependencyProperty as the backing store for Time. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TimeProperty =
DependencyProperty.Register("Time", typeof(string), typeof(MainViewModel), new UIPropertyMetadata(""));
(Date is the same)
Upvotes: 4
Views: 3706
Reputation: 45058
The timer callback is being executed on a thread which is not the UI thread, this causes problems; the reason this is occurring in spite of the fact that you're 'only updating a property' is because such a call creates a chain of calls, namely to notify interested parties of changes to a property, which in this case is the UI, and consequently the scope bubbles up to cause inappropriate cross-thread calls.
To get over this, you can specify the Dispatcher
of your Window
in the timer constructor as the argument for the state
parameter, then use Dispatcher.Invoke
.
For instance...
public MainViewModel()
{
_dateTimer = new Timer(_dateTimer_Tick, Dispatcher, 0, 60000);
}
void _dateTimer_Tick(object state)
{
((Dispatcher)state).Invoke(UpdateUI);
}
void UpdateUI()
{
Time = DateTime.Now.ToString("HH:mm");
Date = DateTime.Now.ToString("D");
}
EDIT:
Using a DispatcherTimer
, as suggested by Henk, and even considered by yourself, may well be the way to go here, however - I simply wasn't aware of the type and therefore was in no position to demonstrate in my answer. With regards to the DispatcherTimer
and performance, on what grounds is your concern founded?
Upvotes: 3