Avatar ·

How to update GUI from another thread in C# WinForms?

Hello, colleagues! I'm a beginner C# developer and I've encountered a problem that's driving me crazy. I have a Windows Forms application that performs a long-running operation (for example, processing a large list of files or downloading data from the internet). To prevent the interface from freezing, I run this operation in a separate thread using `Task.Run` or `Thread`. Here's a simplified example of my code: ```csharp private void buttonStart_Click(object sender, EventArgs e) { Task.Run(() => LongRunningOperation()); } private void LongRunningOperation() { for (int i = 0; i < 100; i++) { // Some work Thread.Sleep(100); // Trying to update ProgressBar progressBar1.Value = i; // Or Label labelStatus.Text = $"Processed