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

manojap

MANOJ AP

Posted on April 12, 2022

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

💖 💪 🙅 🚩
manojap
MANOJ AP

Posted on April 12, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related