Raven
Raven

Reputation: 41

ListView Thread on C#

Can anyone help me with this problem because I don't know how to handle it.

foreach (ListViewItem itemrow in this.listView1.Items)
{
     result = PumpStart.SymbolAdd(itemrow.SubItems[0].Text.Trim());
     if(result != ResultCode.Ok )
     {
          Console.WriteLine("Error adding symbol. " + mgr.ErrorDescription(result));
     }
}

But when I try to run the program, I have this error:

"An exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll but was not handled in user code

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

Thank you very much.

Upvotes: 1

Views: 337

Answers (1)

Mong Zhu
Mong Zhu

Reputation: 23732

If listView1 is responsible for the Cross-thread error, then you will need to use it's Invoke or BeginInvoke method to access and modify data.

As the documentation says:

The Method executes the specified delegate asynchronously on the thread that the control's underlying handle was created on.

In other words: it pulls the piece of code that you want to execute back to the thread which created the Control that you want to modify.

BeginInvoke needs a Delegate as parameter. In this example Action is serving this function:

this.listView1.BeginInvoke(
            new Action(() => 
            {
                foreach (ListViewItem itemrow in this.listView1.Items)
                {
                    result = PumpStart.SymbolAdd(itemrow.SubItems[0].Text.Trim());
                    if(result != ResultCode.Ok )
                    {
                        Console.WriteLine("Error adding symbol. " + mgr.ErrorDescription(result));
                    }
                }
            })
);

Upvotes: 1

Related Questions