DEV Community

MANOJ AP
MANOJ AP

Posted on • Updated on

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

Top comments (0)