DEV Community

MANOJ AP
MANOJ AP

Posted on • Edited on

2 1

Cross-thread operation not valid fix - C# back ground worker

How to fix

When you try to access a component in the UI from a Background Worker DoWork event in C#.net, may end up like this.

System.InvalidOperationException: 'Cross-thread operation not valid: Control 'listView1' accessed from a thread other than the thread it was created on...

Solution

To bypass this error C#.Net provides *invoke * method which execute the **delegate **specified.

Invoke let us directly interact from other threads.

To add items to a listview from a background worker I used the following code snippet which uses a *MethodInvoker **and a **delegate *

listView1.Invoke(new MethodInvoker(delegate
{
item = new ListViewItem("");
item.SubItems.Add(new ListViewItem.ListViewSubItem(item, "Some Column Value Here"));
listView1.Items.Add(item);
}
));

Here is some guides that can save your time how to , snippets-various

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more