Reputation: 21
I have a question on UIElement.Visibility Property.
The following code is executed when the 'StartAll' button is clicked:
private void butStartAllClick(object sender, RoutedEventArgs e)
{
butStartAll.Content = "Running";
LEDInitializing.Visibility = Visibility.Visible;
lblInitializing.Visibility = Visibility.Visible;
Init();
//...rest of code
}
Init then starts up a lengthy initialization routine. My problem is that the visibility attribute is only modified at the end of the Init() method.
How do I get it to update immediately?
I have tried using the Dispatcher like so:
LEDInitializing.Dispatcher.BeginInvoke(
System.Windows.Threading.DispatcherPriority.Normal,
new Action(
delegate()
{
LEDInitializing.Visibility = Visibility.Visible;
}
));
But this doesn't solve my problem.
Any assistance would be greatly appreciated :)
Upvotes: 2
Views: 1067
Reputation: 24453
By running Init
on the UI thread, you are preventing any of the UI changes you make from running until after it completes and butStartAllClick
exits. Depending on what's in Init
you may just be able to run it on a separate thread (4.5 here, use TaskFactory
in 4.0):
private void butStartAllClick(object sender, RoutedEventArgs e)
{
butStartAll.Content = "Running";
LEDInitializing.Visibility = Visibility.Visible;
lblInitializing.Visibility = Visibility.Visible;
Task.Run(() =>
{
Init();
//...rest of code
});
}
If Init
or the following code is doing anything that needs to interact with the UI then you'll need to break it up and use callbacks to the UI to do those updates as needed. The async/await
pattern in 4.5 is usually the easiest way to do this but you can get the same effect in 4.0 with manually set up Task
continuations.
Upvotes: 2