线程中的C#webbrowser getElement

时间:2014-01-09 08:14:28

标签: c# webbrowser-control

我有以下代码:

private void button5_Click(object sender, EventArgs e)
    {
        HtmlElementCollection elc = webBrowser1.Document.GetElementsByTagName("div");
        string text = "Out of sync ... stopping now!";

        foreach (HtmlElement el in elc)
        {
            if (el.GetAttribute("id").Equals("double"))
            {
                if (el.InnerText != "")
                {
                    text = el.InnerText;
                }
            }
        }
        MessageBox.Show(text);
    }

我创建了这个以测试点击互联网网站上的按钮的功能。现在我想反复自动化几个步骤,包括Thread中的这个片段。

代码:

private void button4_Click(object sender, EventArgs e)
    {

        button4.Enabled = false;
        Thread t = new Thread(new ThreadStart(ThreadJob));
        t.Start();
    }

    private void ThreadJob()
    {
        string text = "";
        int countLoss = 0;

        while (running)
        {
            text = checkForNew();
            Thread.Sleep(100);
            if (text.Equals(""))
            {
                for (int i = 0; i < countLoss; i++)
                {
                    halfit();
                }
                countLoss = 0;
                bet();
                Thread.Sleep(2000);
            }
            else
            {
                countLoss++;
                Thread.Sleep(2000);
            }

        }
    }

public string checkForNew()
    {
        HtmlElementCollection elc = webBrowser1.Document.GetElementsByTagName("div");
        string text = "";

        foreach (HtmlElement el in elc)
        {
            if (el.GetAttribute("id").Equals("double"))
            {
                if (el.InnerText != "")
                {
                    if (el.InnerText != null)
                    {
                        text = el.InnerText;
                    }
                }
                else text = "";
            }
        }
        return text;
    }

问题现在,正如你所看到的,我在一个线程中执行了一次基本相同的代码片段,一次没有一个线程。当我在没有Thread的情况下执行它时,它工作正常。但是在线程中,我在方法checkForNew

中的InvalidCastException行获得HtmlElementCollection elc = webBrowser1.Document.GetElementsByTagName("div");

2 个答案:

答案 0 :(得分:1)

您不需要额外的线程来自动执行WebBrowser控制。使用创建WebBrowser的同一线程中的异步逻辑。我回答了类似的问题,并提供了一些值得查看的示例代码:

UI应用:

https://stackoverflow.com/a/19063643/1768303
https://stackoverflow.com/a/20934538/1768303

控制台应用:

https://stackoverflow.com/a/19718530/1768303

答案 1 :(得分:0)

来自WebBrowser类documentation

WebBrowser类只能在设置为单线程单元(STA)模式的线程中使用。要使用此类,请确保使用STAThreadAttribute属性标记Main方法。

因此,如果没有看到您的其他应用程序代码,我怀疑您将需要放弃使用第二个帖子触摸您的UI。