How to update Listview from Background Worker in WinForm-C#.Net ?

How to solve ‘Cross-thread operation not valid: error in C# Background Worker


C# WinForm provides Background Worker Control that is capable of run asynchronous job in background. This must be ideal for fetching data in the background .

What about updating UI from background ? Like update a listview items from database . Let’s begin from setup.

How to ?

The Background Worker control has a event ,DoWork where we can add our background tasks.

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
{
// logic here         
}

We can use the RunWorkerCompleted to apply logic which will executed after completion.

In the form load event (or from any event ) you can start the task by running

   this.backgroundWorker1.RunWorkerAsync();

Problem with UI and Worker

When you try to access a component in the UI from a Background Worker DoWork event, 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.

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

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

I hope this will help you and recommend the following snippets.

Author: Manoj

Developer and a self-learner, love to work with Reactjs, Angular, Node, Python and C#.Net

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.