views:

350

answers:

4

Hi!

I have a task that takes a long time. I do it with a background worker thread and before start it, since Do_Work I begin an animation over a label and when task finishes, I stop it in RunWorkerCompleted but I received an error because I try to begin/stop animation in the background thread that is not the owner. How can I do this, I mean to begin/stop animation in the background worker?

thanks!

+1  A: 

You should start the animation before starting the BackgroundWorker, not in the DoWork event. That way, you will be able to stop it from the RunWorkerCompleted event.

Thomas Levesque
A: 

You need to use the Dispatcher.BeginInvoke method, on the control which is doing the animation.

jlew
A: 

You can also call the stop animation on the UI thread using something like the following:

private void OnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    /* If not operating on the main UI thread, call this method again on the App dispatcher's thread */
    if (App.Current != null && App.Current.Dispatcher.Thread != Thread.CurrentThread)
    {
        App.Current.Dispatcher.Invoke(new RunWorkerCompletedEventHandler(OnRunWorkerCompleted), new object[] { sender, e});
        return;
    }

    // Do stuff to the UI here
}
Andy Shellam
A: 

Ok!

Thanks very much for all your answers. All them are great.

I'll try it tomorrow.

One thing, I am a bit confused between DoWork and RunWorkerCompleted event, sorry to post it here. As I understand, in DoWork it is not possible to modify directly the controls states as they haven't been created in it, it must be done through a Dispatcher.Invoke or the others methods you say. In RunWorkerCompleted event, is it possible to modify directly without doing it through one of the methods posted? Why is it possible to modify directly in RunWorkerCompleted and not in DoWork? Is it because in RunWorkerCompleted event the background worker thread has already finished?

Thanks.

toni
That's exactly right. `RunWorkerCompleted` is executed on the UI thread after `DoWork` is finished. Note that you can also update the UI in the `ReportProgress` event handler, which also runs on the UI thread. I never use `Dispatcher.Invoke` to update the UI from a `BackgroundWorker` myself; I like the separation of concerns that `DoWork` and `ReportProgress` provide.
Robert Rossney