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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay