如何在backgroundworker内部更改ListView?跨线程错误

本文关键字:ListView 线程 错误 backgroundworker 内部 | 更新日期: 2023-09-27 17:49:18

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

我在运行程序时出错。。。。{"跨线程操作无效:控件'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?

我知道在一些教程中说使用invoke?但我尝试了很多东西,但还是错了?

有手吗?

如何在backgroundworker内部更改ListView?跨线程错误

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

   ListViewItem abg = new ListViewItem(isititle3);

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

删除最后一行(listView1.Items.Add(abg(;//这里有错误?(从您的代码中删除,并将其替换为:

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

这就可以完成任务了,亲爱的!

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

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