0

I have a progress bar in WPF, I set a storyboard animation to it from 0-90 fillup over x period of time which may change based on the task that is being performed.

Would it be possible to allow its storyboard animation to play out in a different thread then interject into it to change various properties of the progress bar when needed?

Ben Walker
  • 2,037
  • 5
  • 34
  • 56
meds
  • 21,699
  • 37
  • 163
  • 314
  • 2
    You can use [Dispatcher.Invoke][1] from another thread. [1]: http://stackoverflow.com/questions/1644079/how-can-i-use-the-dispatcher-invoke-in-wpf-change-controls-from-non-main-thread – Larry Sep 20 '12 at 04:19
  • What exactly is the different thread supposed to solve? – H H Sep 20 '12 at 10:06

2 Answers2

3

Although Laurent probably answers your actual question, the correct answer is no.

The Progressbar can only run on the UI thread.

It is the process that reports progress to the ProgressBar that can run on a different thread but the update of the ProgressBar needs to run on the UI thread.

The setup you propose might lead to a ProgressBar that does NOT give the correct status of the job. It is probably better to have the process report its status instead of trying to sync both the process and the animation.

The animation might need to run on the UI thread as well because you are probably binding a property of the ProgressBar to the animation.

Emond
  • 50,210
  • 11
  • 84
  • 115
2

Per Laurent's comment ...

void startProgress()
{
    ThreadStart ts = new ThreadStart(Go);
    Thread t = new Thread(ts);
    t.Start();
}

void Go()
{
    double val = 0;
    while (val < 100)
    {
        Thread.Sleep(50);
        Dispatcher.Invoke(new action(() =>
        {
            MyProgressBar.Value += 0.5;
            val = MyProgressBar.Value;
        }));
    }
}

delegate void action();
McGarnagle
  • 101,349
  • 31
  • 229
  • 260