private void button1_Click(object sender, EventArgs e)
        {
            Thread th = new Thread(new ThreadStart(fangfa));
            th.Start();
        }        private void fangfa()
        {
            WebBrowser webbrowser1 = new WebBrowser();
            webbrowser1.Navigate("http://www.163.com");            while (webbrowser1.ReadyState != WebBrowserReadyState.Complete)
                Application.DoEvents();
            string strHTML = webbrowser1.DocumentText;
            MessageBox.Show("fangfa");
        }
就是线程里的方法里有控件的情况,会报错“cannot be instantiated because the current thread is not in a single-threaded apartment.”就是说当前线程不是单线程,这种情况一般怎么处理呢。谢谢大家帮我看下。

解决方案 »

  1.   

    th.SetApartmentState(ApartmentState.STA);
      

  2.   

    从.net2.0开始,默认情况下,控件只能被创建它的线程访问,其他被其他线程访问。
    如果你想关闭这种限制,可以把控件.CheckForIllegalCrossThreadCalls属性设为False。
    这样就可以直接从任何线程访问任何控件了,但是这种方法是不安全的。
      

  3.   

    th.SetApartmentState(ApartmentState.STA)
      

  4.   

    不可以跨线程操作WebBrowser,不考虑安全性的话,可以像 liuyilin999 所讲的一样,设置一下CheckForIllegalCrossThreadCalls=false.也可以在线程中动态创建WebBrowser
      

  5.   

    th.SetApartmentState(ApartmentState.STA);这个是可以的。
    CheckForIllegalCrossThreadCalls=false.
    这个不行。th.SetApartmentState(ApartmentState.STA);这个也有安全隐患吗?是不是设置线程什么状态的吧
      

  6.   

    控件只能被创建他的线程使用。
    一般是主线程。
    线程中可以使用Invoke来更新界面层
      

  7.   


    private void button1_Click(object sender, EventArgs e)
            {
                Thread th = new Thread(new ThreadStart(runcode));
                th.Start();
            }
    private void runcode()
    {
        WebBrowser.invoke(fangfa)
    }
            private void fangfa()
            {
                WebBrowser webbrowser1 = new WebBrowser();
                webbrowser1.Navigate("http://www.163.com");            while (webbrowser1.ReadyState != WebBrowserReadyState.Complete)
                    Application.DoEvents();
                string strHTML = webbrowser1.DocumentText;
                MessageBox.Show("fangfa");
            }
    你现在的问题就是跨线程访问控件,需要使用控件的invoke方法来进行调用