4

可能重复:
避免跨线程操作错误的最简洁和正确的方法?

运行我的程序时出现错误.... {“跨线程操作无效:控件 'listView1' 从创建它的线程以外的线程访问。”}

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {
        TestObject argumentTest = e.Argument as TestObject;
        string[] lines = argumentTest.ThreeValue.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);

        HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
        foreach (string vr in lines)
        {
            string country = argumentTest.OneValue.Trim();
            string url = vr + country + '/code/' + argumentTest.TwoValue.Trim();
            string sourceCode = WorkerClass.getSourceCode(url);

            document.LoadHtml(sourceCode);
            var title = document.DocumentNode.SelectSingleNode("//title");
            var desc = document.DocumentNode.SelectSingleNode("//div[@class='productDescription']");

            //-- eksekusi title
            string isititle = title.InnerText;
            string isititle2 = isititle.Replace("droidflashgame: ", "");
            string isititle3 = Regex.Replace(isititle2, "[^A-Za-z0-9 ]+", "");
            string isititle4 = isititle3.Substring(0, Math.Min(isititle3.Length, 120));
            //-- Adding to list view for next step...
            ListViewItem abg = new ListViewItem(isititle3);
            abg.SubItems.Add(isititle4);
            listView1.Items.Add(abg); // ERROR in Here?

我知道在一些教程中说使用调用?但我尝试了很多东西但仍然错误?

有手吗?

4

3 回答 3

9

试试这个。这对我来说很好

   ListViewItem abg = new ListViewItem(isititle3);


     if (listView1.InvokeRequired)
                    listView1.Invoke(new MethodInvoker(delegate
                    {
           listView1.Items.Add(abg);           

                    }));
                else
           listView1.Items.Add(abg);    
于 2012-12-24T08:41:48.530 回答
2

从您的代码中删除最后一行 (listView1.Items.Add(abg); // ERROR in Here?) 并将其替换为:

AddListViewItem(abg);

然后将此方法应用于您的代码:

    delegate void AddListViewItemDelegate(ListViewItem abg);
    void AddListViewItem(ListViewItem abg)
    {
        if (this.InvokeRequired)
        {
            AddListViewItemDelegate del = new AddListViewItemDelegate(AddListViewItem);
            this.Invoke(del, new object() { abg });
        }
        else
        {
            listView1.Items.Add(abg);
        }
    }

这将完成工作,快乐编码!

于 2012-12-24T09:06:22.750 回答
0

当您使用后台工作人员时,您可以简单地通过更改进度来传递项目:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        //..........
        var test = new ListViewItem("test");
        backgroundWorker1.ReportProgress(0, test);


    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        listView1.Items.Add((ListViewItem)e.UserState);
    }
于 2012-12-24T08:50:29.307 回答