【发布时间】: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