-1

I'm trying use thread to leech link from website, but when i trying run . It show error:

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

My code:

try
{
    foreach (HtmlNode node in (IEnumerable<HtmlNode>)document.DocumentNode.SelectNodes("//table[@class='tbl' and @id='stats']//tr[@class='' or @class='bg']"))
    {
    HtmlAgilityPack.HtmlDocument document2 = new HtmlAgilityPack.HtmlDocument();
    document2.LoadHtml(node.InnerHtml);
    try
    {
    string str6 = document2.DocumentNode.SelectSingleNode("//td[2]//a").Attributes["href"].Value;
    string innerText = document2.DocumentNode.SelectSingleNode("//td[2]//a").InnerText;
    string[] items = new string[] { listView1.Items.Count + 1.ToString(), innerText, str6, "" };
    ListViewItem item = new ListViewItem(items);
    listView1.Items.Add(item);
    listView1.EnsureVisible(listView1.Items.Count - 1);
    }
    catch (Exception ex)
    {
    MessageBox.Show(ex.Message);
    }
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

1 Answers1

5

This is because of Thread affinity of controls. Those can be updated only on thread they were created. InvokeRequired and Invoke gives method to update the control on same thread:

        if (listView1.InvokeRequired)
        {
            listView1.Invoke((MethodInvoker) delegate()
            {
                ListViewItem item = new ListViewItem(items);
                listView1.Items.Add(item);
                listView1.EnsureVisible(listView1.Items.Count - 1); 
            });
        }
Nitin
  • 18,344
  • 2
  • 36
  • 53
  • There there. I think I last used this before lambdas were added ;) But usually to avoid duplicated code, I did it with an else and the actual code on the listview defined outside once. – BitTickler Apr 23 '16 at 03:37
  • 1
    Low quality answer compared to hundreds of existing duplicates of this question. If you going for canonical post make sure to put at least some effort – Alexei Levenkov Apr 23 '16 at 03:41