Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I'm struggling with what should be a simple task; update the user interface in a WPF program to reflect progress. I know there are different ways to do this but please can someone point out where I'm going wrong with this simple approach?

Thanks, stegzzz

C#
/// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        delegate void MDFunc(int i);

        //after clicking the Go button a set of calls to Func are queued
        private void Go(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < 10; i++)
                this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new MDFunc(Func), i);

        }

        //each time Func is called (from the dispatcher queue) it should update the button content so the user sees
        //the task progress
        void Func(int i)
        {
            Stopwatch S = new Stopwatch();
            S.Start();
            while (S.ElapsedMilliseconds < 500)
            { }

            button1.Content = i.ToString();
            button1.InvalidateVisual();
        }
    }
Posted

The timer thread should perform the while loop and at the desired interval, send a message back to the form which can then use Dispatcher.Invoke to update the button.


At least, that's the way I'd do it.
 
Share this answer
 
It turns out that the approach sketched above, in the question, is actually OK but appears not to work because of DispatcherPriority.Normal

Setting DispatcherPriority to a lower level than render has the desired effect, in that the screen updates to reflect progress through the i calls of Func which are setup in the Go loop. Presumeably, when priority is normal, all of the calls to Func get completed before the next render operation and that's why I wasn't seeing the screen update.

The other suggestion from John maybe is OK for a forms application?

Chrs, stegzzz
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900