0

Why do I get at "ListViewItem lviFile = lvFiles.Items[i];" a cross-thread error, even if I use DoWorkEventArgs e for the ListView argument?

private void btUpload_Click(object sender, EventArgs e)
{
    bwUpload.RunWorkerAsync(lvFiles);
}

private void bwUpload_DoWork(object sender, DoWorkEventArgs e)
{
    ListView lvFiles = (ListView)e.Argument;

    for (int i = 0; i < lvFiles.Items.Count; i++)
    {
        ListViewItem lviFile = lviFile.Items[i];
        ...
    }
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291

3 Answers3

2

Since you're accessing it from a separate thread, you will need to use Invoke in order to use it.

private void btUpload_Click(object sender, EventArgs e)
{
    bwUpload.RunWorkerAsync(lvFiles);
}

private void bwUpload_DoWork(object sender, DoWorkEventArgs e)
{
    ListView lvFiles = (ListView)e.Argument;

    for (int i = 0; i < lvFiles.Items.Count; i++)
    {
        Invoke(new MethodInvoker(() =>
        {
            ListViewItem lviFile = lviFile.Items[i];
            ...
        });
    }
}
ThePerplexedOne
  • 2,920
  • 15
  • 30
  • I have to write all inside the Invoke(), or how can i access the ListViewItem outside the Invoke()? It seems complicated for debuging, if I write all inside of the Invoke()... –  Oct 05 '16 at 16:09
  • You can't access it outside of the invoke, that's why it's there... – ThePerplexedOne Oct 06 '16 at 08:40
0

If you want to use a control. you have to invoke the task in the thread the control is created in.

More info Here

Pepernoot
  • 3,409
  • 3
  • 21
  • 46
0

You should be using the BackgroundWorker.ProgressChanged to update the UI with the changes from the DoWork() method. Calling ReportProgress() on the BackgroundWorker allows you to pass an object as the second argument which you can then use in the ProgressChanged event.

Ric
  • 12,855
  • 3
  • 30
  • 36
  • I dont want to update my ListView while DoWork(). I need the values from the ListViewItem... –  Oct 05 '16 at 16:05
  • But you are accessing `lvFiles` on a different thread which is causing you problems. `ProgressChanged` is where you can access these values without the exception. – Ric Oct 05 '16 at 16:13