Cross-thread operation not valid: how to access controls from another thread in C# WinForms
Hello everyone! I'm a beginner in C# and WinForms, and I'm stuck on a multithreading problem. I'm writing an application that loads data from the internet and displays it in a ListBox. To prevent the interface from freezing, I run the loading in a separate thread via Task.Run. Here's simplified code:
```csharp
private void buttonStart_Click(object sender, EventArgs e)
{
Task.Run(() => LoadData());
}
private void LoadData()
{
for (int i = 0; i < 10; i++)
{
// Simulating data loading
Thread.Sleep(1000);
// Trying to add an item to ListBox
listBoxResult.Items.Add("Element " + i);
}
}
```
When running, on the line `listBoxResult.Items.Add(...)` an exception is thrown: "Cross-thread operation not valid: Control 'listBoxResult' accessed from a thread other than the thread it was created on."