Click here to Skip to main content
15,889,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm having trouble updating a WPF ProgressBar from an event handler. I created a dummy c# class with a long running method that fires events. My WPF app declares an instance of this class, subscribes to the event, then tries to update the ProgressBar "value" property from the event handler. The ProgressBar does not respond to the updates until the very end when all the updates happen at once.

I realize this is the classic symptom of trying to update the UI from some other thread, but I think I've tried all the classic solutions to that problem, but none seem to work.

Surely I'm missing something... Code as follows.

What I have tried:

Here's the UI side

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

        private void Window_ContentRendered(object sender, EventArgs e)
        {
            BackgroundWorker worker = new BackgroundWorker();
            worker.WorkerReportsProgress = true;
            worker.DoWork += worker_DoWork;
            worker.ProgressChanged += worker_ProgressChanged;

            worker.RunWorkerAsync();
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 0; i < 100; i++)
            {
                (sender as BackgroundWorker).ReportProgress(i);
                Thread.Sleep(100);
            }
        }

        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            pbStatus.Value = e.ProgressPercentage;
        }
    }
}


Here's the class
C#
public class DownloadEventArgs : EventArgs
{
    public int progress { get; set; }

    public DownloadEventArgs() { }
    public DownloadEventArgs(int prog)
    {
        progress = prog;
    }
}

public delegate void DownloadProgressNotifier(object sender, DownloadEventArgs e);
public class Downloader
{
    public event DownloadProgressNotifier DownloadProgress;
    public Downloader() { }

    public void Download()
    {
        for(int i = 0; i < 100; i++)
        {
            Thread.Sleep(100);

            DownloadEventArgs args = new DownloadEventArgs(i);

            OnDownloadProgress(args);
        }
    }
    protected virtual void OnDownloadProgress(DownloadEventArgs e)
    {
        if(DownloadProgress != null)
        {
            DownloadProgress(this, e);
        }
    }
}
Posted
Comments
Jitesh Hirani 3-Aug-16 6:07am    
Try to update your progressbar value in Dispatcher.

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