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
namespace ProgressBoxUpdates
{
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
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);
}
}
}