CodexBloom - Programming Q&A Platform

WinForms: implementing Refreshing ProgressBar Control During Long-Running Operations

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-18
winforms backgroundworker progressbar ui-thread C#

I'm stuck trying to I tried several approaches but none seem to work... I tried several approaches but none seem to work. I'm experiencing an scenario with the `ProgressBar` control in a WinForms application when I execute a long-running operation on a button click. The UI becomes unresponsive, and the `ProgressBar` does not update as expected. I'm using .NET Framework 4.8 and the `BackgroundWorker` component to handle the operation. Here's a simplified version of my code: ```csharp private void btnStart_Click(object sender, EventArgs e) { ProgressBar progressBar = new ProgressBar(); progressBar.Minimum = 0; progressBar.Maximum = 100; progressBar.Value = 0; this.Controls.Add(progressBar); BackgroundWorker worker = new BackgroundWorker(); worker.WorkerReportsProgress = true; worker.DoWork += (s, args) => { for (int i = 0; i <= 100; i++) { System.Threading.Thread.Sleep(50); // Simulate long operation worker.ReportProgress(i); } }; worker.ProgressChanged += (s, args) => { progressBar.Value = args.ProgressPercentage; }; worker.RunWorkerCompleted += (s, args) => { MessageBox.Show("Operation Completed!"); }; worker.RunWorkerAsync(); } ``` The question is that when I click the button, the `ProgressBar` appears to hang at `0%` until the operation is fully completed, which is quite misleading. I also see an occasional `InvalidOperationException` stating that the control want to be accessed from a thread other than the thread it was created on. I tried ensuring that the UI updates are performed on the UI thread by using the `ReportProgress` method of `BackgroundWorker`, but it seems the initial addition of the `ProgressBar` to the form is blocking the UI thread. I also considered using `Task.Run()` with `async` and `await`, but I prefer to keep this implementation simple for now. What am I missing here? Is there a better way to handle the `ProgressBar` updates during long-running tasks while ensuring the UI remains responsive? Any help would be greatly appreciated! Any help would be greatly appreciated! I'm working on a REST API that needs to handle this.