CodexBloom - Programming Q&A Platform

WinForms: Using BackgroundWorker to Update UI with Progress Reporting Causes Cross-Thread Operation Exception

πŸ‘€ Views: 1390 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-26
winforms backgroundworker cross-threading C#

I'm working through a tutorial and I'm stuck on something that should probably be simple. I'm working on a project and hit a roadblock. I'm working on a WinForms application where I need to perform a lengthy operation (like downloading files) in the background while updating a ProgressBar on the UI. I've implemented a `BackgroundWorker`, but I'm encountering a `Cross-thread operation not valid: Control 'progressBar1' accessed from a thread other than the thread it was created on` exception whenever I try to update the ProgressBar inside the `RunWorkerCompleted` event. Here’s a simplified version of my code: ```csharp private void btnStart_Click(object sender, EventArgs e) { BackgroundWorker worker = new BackgroundWorker(); worker.WorkerReportsProgress = true; worker.DoWork += Worker_DoWork; worker.RunWorkerCompleted += Worker_RunWorkerCompleted; worker.ProgressChanged += Worker_ProgressChanged; worker.RunWorkerAsync(); } private void Worker_DoWork(object sender, DoWorkEventArgs e) { for (int i = 0; i <= 100; i++) { // Simulate long-running task System.Threading.Thread.Sleep(50); (sender as BackgroundWorker).ReportProgress(i); } } private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e) { progressBar1.Value = e.ProgressPercentage; } private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { MessageBox.Show("Operation completed"); // The error occurs here when trying to update UI controls progressBar1.Value = 0; } ``` I've ensured that I'm using the `ReportProgress` method to update the ProgressBar, which seems correct, but I still get the exception in the `RunWorkerCompleted` event. What am I missing, and how can I safely update my UI without encountering this exception? My development environment is Ubuntu. Thanks in advance! I'm on Linux using the latest version of C#. Any ideas how to fix this?