Avatar ·

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

Hi everyone! I'm a beginner C# developer and I'm writing a small WinForms application. I have a button that, when clicked, starts a long-running operation (e.g., downloading data from the internet or processing a large file). I want the interface to remain responsive during this operation, so I run it in a separate thread using `Task.Run`. The problem occurs when I try to update UI elements (e.g., ProgressBar, Label, or TextBox) from this background thread. The application crashes with an exception: "InvalidOperationException: Cross-thread operation not valid. Control 'progressBar1' accessed from a thread other than the thread it was created on." Here's an example of my code: ```csharp private void buttonStart_Click(object sender, EventArgs e) { Task.Ru