2016-04-23 94 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

與此問題的數百個現有重複相比,質量較差的答案。如果你打算進行規範的發佈,請務必至少付出一些努力 –