CodexBloom - Programming Q&A Platform

Windows Forms application throws 'InvalidOperationException' when accessing UI controls from a non-UI thread

👀 Views: 76 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-01
c# windows-forms async-await multithreading C#

I've hit a wall trying to Quick question that's been bugging me - I'm developing a Windows Forms application using .NET 5.0 where I'm trying to update some UI controls from a background thread... The intention is to fetch data asynchronously from a web API and then update the UI with the results. However, when I attempt to update the UI controls, I get the following error: ``` System.InvalidOperationException: Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on. ``` To mitigate this, I tried using `Invoke` to marshal the call back to the UI thread, but I'm still encountering the same exception. Here's the relevant code snippet: ```csharp private async void btnFetchData_Click(object sender, EventArgs e) { // Simulating background work await Task.Run(() => { // Fetch data from API var data = FetchDataFromApi(); // Attempting to update UI directly here label1.Text = data; }); } private string FetchDataFromApi() { // Simulate a delay Thread.Sleep(2000); return "Fetched data!"; } ``` I replaced the direct assignment to `label1.Text` with an `Invoke` call like this: ```csharp private async void btnFetchData_Click(object sender, EventArgs e) { await Task.Run(() => { var data = FetchDataFromApi(); this.Invoke((MethodInvoker)delegate { label1.Text = data; }); }); } ``` However, I still receive the same `InvalidOperationException`. I checked to ensure the `Invoke` is being used, but I must be missing something. Is there a specific pattern I should follow when updating UI components from a background task? Any insights would be greatly appreciated! My development environment is Linux. I'd really appreciate any guidance on this. I'm on Windows 11 using the latest version of C#. I'd love to hear your thoughts on this.