【问题标题】:c# - Cross-thread operation not valid ListView [duplicate]c# - 跨线程操作无效ListView [重复]
【发布时间】:2016-04-23 03:29:31
【问题描述】:

我正在尝试使用线程从网站中获取链接,但是当我尝试运行时。它显示错误:

跨线程操作无效:控件“listView1”从创建它的线程以外的线程访问

我的代码:

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

【问题讨论】:

  • InvokeRequired 会员属性是你的朋友 ;)
  • 如何添加 InvokeRequired ?
  • 缩进也是你的朋友。请。
  • 你不需要添加它。它已经在那里了。在您的列表视图中。基本上它会告诉您是否可以继续,或者您是否需要编组对 GUI 线程(STAThread ...)的调用。您可以执行以下操作:if( this.InvokeRequired ) { this.Invoke(...) } 记不起调用的确切语法,因为我很久没有使用 C#了。

标签: c# multithreading winforms


【解决方案1】:

这是因为控件的线程亲和性。这些只能在它们创建的线程上更新。 InvokeRequiredInvoke 提供了在同一线程上更新控件的方法:

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

【讨论】:

  • 那里。我想我最后一次使用它是在添加 lambdas 之前;)但通常为了避免重复代码,我使用 else 来完成它,并且 listview 上的实际代码在外部定义一次。
  • 与该问题的数百个现有重复项相比,答案质量较低。如果您要发布规范帖子,请确保至少付出一些努力
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-22
  • 1970-01-01
  • 2011-03-27
  • 1970-01-01
  • 1970-01-01
  • 2010-12-04
相关资源
最近更新 更多