Hi, a few days ago I was trying to write a WPF application that needed to update a progress bar whilst in a loop. I searched around on the internet and finally found a solution, however, I don't actually know how it works. Here is the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace bar_test
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public delegate void emptyDelegate();

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < 100; i++)
            {
                progressBar1.Value = i;
                progressBar1.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Render, (emptyDelegate)delegate { });
                System.Threading.Thread.Sleep(10);
            }
        }
    }
}

The bit that I don't understand is the

(emptyDelegate)delegate { }

. I declared the delegate my self at the beggining and I get how that works, I just don't see what this part is doing, and what is the point in even having the delegate there in the first place? I would be very grateful if some one could explain what is actually going on.

Thanks

As far as I can tell it is there because Invoke needs a delegate.
The invoke call on the dispatcher is causing progressbar to refresh.
I think the Windows Forms equivalent is progressbar.Invalidate().
It forces the progress bar to re-paint (render) itself; with the new value.
If you don't like it being empty, then you can always move the progressBar1.Value = i; in to it.

for (int i = 0; i < 101; i++)
            {
                progressBar1.Dispatcher.Invoke(
                    System.Windows.Threading.DispatcherPriority.Render,
                    (Action)delegate { progressBar1.Value = i; });
                System.Threading.Thread.Sleep(10);
            }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.