2016-04-23 52 views
-2

我想使用线程从网站水蛭链接,但是当我尝试运行。它显示错误:c# - 跨线程操作无效ListView

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

我的代码:

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); 
} 
+0

''InvokeRequired''成员属性是你的朋友;) – BitTickler

+0

如何添加InvokeRequired? –

+0

缩进也是你的朋友。请。 –

回答

1

这是因为控制线程关联的。这些只能在创建线程时更新。 InvokeRequiredInvoke给出的方法更新相同的线程控制:

 if (listView1.InvokeRequired) 
     { 
      listView1.Invoke((MethodInvoker) delegate() 
      { 
       ListViewItem item = new ListViewItem(items); 
       listView1.Items.Add(item); 
       listView1.EnsureVisible(listView1.Items.Count - 1); 
      }); 
     } 
+0

那里。我想我最后在添加lambdas之前使用了这个);但通常为了避免重复的代码,我使用else和实际的listview中的代码在外面定义了一次。 – BitTickler

+0

与此问题的数百个现有重复相比,质量较差的答案。如果你打算进行规范的发布,请务必至少付出一些努力 –