none
多线程中操作 webBrowser 出错 RRS feed

  • 问题

  • 在多线程中操作出错,提示"指定的转换无效",如果我用委托是不出错了,但是界面不刷新了(线程中对网页进行分析,较耗时),像死了一样,这样的话效果就与单线程效果一样了,请问如何解决?

    附代码:
            private void button3_Click(object sender, EventArgs e)
            {
                th = new System.Threading.Thread(new System.Threading.ThreadStart(Test));
                th.Start();
               
            }


            public delegate void DelUserHandler();
            private void Test()
            {
                if (this.webBrowser1.InvokeRequired)
                {
                    DelUserHandler handler = new DelUserHandler(Test);
                    this.Invoke(handler);
                }
                else
                {

                    Boolean flag = true;
                    while (flag)
                    {
                        HtmlDocument doc = webBrowser1.Document;
                        if (SearchText(doc.All, 0))
                        {
                            flag = false;
                            textBox4.Text = iPage.ToString() + " 找到了";
                        }
                        else
                        {
                            foreach (HtmlElement tag in doc.All)
                            {
                                foreach (HtmlElement vtag in tag.All)
                                {
                                    if (vtag.InnerText == "下一页面")
                                    {
                                        iPage++;
                                        vtag.InvokeMember("Click");
                                        System.Threading.Thread.Sleep(5000);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            private Boolean SearchText(HtmlElementCollection all,int Level)
            {
                int i = 0;
                foreach (HtmlElement tag in all)
                {
                    //处理
                    if (tag.GetAttribute("href").IndexOf(@"xxxxxxxxxxxx/") >= 0)
                    {
                        tag.InvokeMember("Click");
                        return true;
                    }

                    //查找子级
                    if(tag.All.Count>0)
                    {
                        if (SearchText(tag.All, Level + 1))
                            return true;
                    }
                    iIndex++;
                }
                return false;
            }

    2009年6月30日 10:59

答案

全部回复