Thursday, March 19, 2009

Updating Silverlight User Interface From Timer

Updating a Silverlight based user interface from a timer may not work as expected. The reason is that the timer thread is different from the user interface thread. Only the user interface thread can update a Silverlight based user interface. So for instance the following code will not work in a Silverlight application:
// _statusMessage is a System.Windows.Controls.TextBlock object
// _statusMessageTime is a System.Threading.Timer object
private void DisplayStatusMessage(string message) {
  _statusMessage.Text = message;
  _statusMessageTimer = new Timer(ResetStatusMessageCallback,
                            /* params left out for brevity */);
}

private void ResetStatusMessageCallback(object stateInfo) {
  _statusMessage.Text = "";
}
When the timer fires the callback is executed on a thread different to the user interface thread. The UI will not update. In my installation the Silverlight interface would then simply disappear! To fix this you need a way to execute the actual update on the user interface thread. One way is to use the Dispatcher object (Namespace: System.Windows.Threading) of the XAML page. Then the code of the callback implementation looks as follows:
private void ResetStatusMessageCallback(object stateInfo) {
  Dispatcher.BeginInvoke(() => {
                         _statusMessage.Text = "";
                         });
}
Another solution would be to use the DispatcherTimer. I spare you the details but you can check here for an example.

No comments:

Post a Comment

All comments, questions and other feedback is much appreciated. Thank you!