如何更改ListView里面的backgroundworker?跨线程错误 [英] How to Changing ListView inside backgroundworker? Cross-Thread Error

查看:101
本文介绍了如何更改ListView里面的backgroundworker?跨线程错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

运行我的程序时出错...
{跨线程操作无效:控制'listView1'从线程访问其他比它创建的线程。}

I got error when running my programs.... {"Cross-thread operation not valid: Control 'listView1' accessed from a thread other than the thread it was created on."}

    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吗?但是我尝试过很多东西,但仍然错误?

I knew in some tutorial said using invoke? but I tried many thing but still error?

任何手?

推荐答案

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

Try this .This works fine for me

   ListViewItem abg = new ListViewItem(isititle3);


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

                    }));
                else
           listView1.Items.Add(abg);    

这篇关于如何更改ListView里面的backgroundworker?跨线程错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆