How does one execute several UI updates from a Silverlight callback?
For example, I would like the user to click a button, have the UI make a change, do some work, then make another change… instead, the user clicks the button and the callback seems to execute in the background and then all of the UI changes flash before my eyes.
MainPage.xaml:
<Grid x:Name="LayoutRoot" Background="White" >
<TextBlock Height="23" Name="textBlock1" Text="TextBlock" VerticalAlignment="Top"/>
<Button Click="button1_Click" Content="Button" Height="23" Name="button1" Width="75" />
</Grid>
MainPage.xaml.cs:
private void button1_Click(object sender, RoutedEventArgs e)
{
textBlock1.Text = "1";
// also tried Thread.Sleep(5000);
Dispatcher.BeginInvoke(() => Thread.Sleep(5000));
textBlock1.Text = "2";
}
Silverlight uses a queue of work items to handle rendering and logic on the UI thread. Since your logic also runs on the UI thread (in your
button_Clickhandler) the renderer doesn’t get a chance to draw the screen until your method is done executing AND the internal message loop gets around to drawing the screen.Your
BeginInvokeimmediately places your function on the Silverlight work queue to execute on the UI thread (and returns immediately). The order Silverlight processes this is probably something like:button_Click(which places a new action on the work queue)Thread.Sleepaction, pausing the UI thread for 5 secondsWhat you want to do is start a new thread to do your work, then
BeginInvokeback to the UI thread:I should add that Silverlight 5 adds a composition thread that can perform certain actions to update the UI without blocking the UI thread like playing animations and doing GPU accelerated rendering where possible.