Reputation: 21726
I have button on my window. After user clickes the button i want my application to animate loading label (with rotationg it), during the other thread gets some data from database. After loading data from DB animation must end. The task seems simple , but it doesn't work. The problem is that animation whatever i do animation starts only after loading from the database when it is not needed.
Help please. Here some code:
private void LoginButtonClick(object sender, RoutedEventArgs e)
{
Thread thread = new Thread(new ThreadStart(
delegate()
{
DispatcherOperation dispatcherOp =
this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(
delegate()
{
var da = new DoubleAnimation(360, 0, new Duration(TimeSpan.FromSeconds(1)));
var rt = new RotateTransform();
loadingLabel.RenderTransform = rt;
loadingLabel.RenderTransformOrigin = new Point(0.5, 0.5);
da.RepeatBehavior = RepeatBehavior.Forever;
rt.BeginAnimation(RotateTransform.AngleProperty, da);
}));
dispatcherOp.Completed += new EventHandler(DispatcherOpCompleted);
}));
thread.Start();
}
void DispatcherOpCompleted(object sender, EventArgs e)
{
//Loading From Database
}
Upvotes: 0
Views: 2477
Reputation: 20150
The Dispatcher.Completed event is executed on the main UI thread. Your worker thread is just queueing the dispatcher operation and exiting. Instead of creating a thread that starts the animation and then doing your database loading in the Completed handler, just start your animation in the main thread, and then create a worker thread to do the database loading.
private void LoginButtonClick(object sender, RoutedEventArgs e)
{
var da = new DoubleAnimation(360, 0, new Duration(TimeSpan.FromSeconds(1)));
var rt = new RotateTransform();
loadingLabel.RenderTransform = rt;
loadingLabel.RenderTransformOrigin = new Point(0.5, 0.5);
da.RepeatBehavior = RepeatBehavior.Forever;
rt.BeginAnimation(RotateTransform.AngleProperty, da);
Thread thread = new Thread(new ThreadStart(LoadData));
thread.Start();
}
void LoadData()
{
//Loading From Database
// Use a Dispatch.BeginInvoke here to stop the animation
// and do any other UI updates that use the results of the database load
}
Upvotes: 3