private void btnStart_Click(object sender, EventArgs e)
        {
           
            if (btnStart.Text == "开始")
            {
                btnStart.Text = "暂停";
                flag = true;
            }
            else
            {
                btnStart.Text = "开始";
                flag = false;
            }
            CreateThread();
            
        }
        private void CreateThread()
        {
            dothread = new DoThread();
            Thread thread = new Thread(new ThreadStart(dothread.interfaceMsg));
            Thread threadTwo = new Thread(new ThreadStart(MsgTwo));
            thread.Start();
            threadTwo.Start();
        }
        public void MsgTwo()
        {
            while (flag)
            {
                ListViewBind();
            }
        }
        private void ListViewBind()
        {
            Thread.Sleep(1000);
            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(ListViewBind));
            }
            else
            {
            }
        private void BtnBegin_Click(object sender, EventArgs e)
        {
            Thread threadOne = new Thread(new ThreadStart(ListViewLog));
            threadOne.Start();
        }
  private void ListViewLog()
        {
            
            
                int count = 0;
                this.saveFileDialog1.DefaultExt = ".txt";
                saveFileDialog1.Filter = "Word文件(*.doc)|*.doc|文本文件(*.txt)|*.txt|所有合适文件(*.doc/*.txt)|*.doc/*.txt";
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    string filename = saveFileDialog1.FileName;
                    FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write);
                    StreamWriter sw = new StreamWriter(fs);
                    sw.Flush();
                    sw.BaseStream.Seek(0, SeekOrigin.Begin);
                    while (count < this.listView2.Items.Count)
                    {
                        sw.WriteLine(listView2.Items[count].SubItems[1].Text.Trim());
                        count = count + 1;
                    }
                    sw.Flush();
                    fs.Close();
                }
            }
当运行这段代码的时候会在if (saveFileDialog1.ShowDialog() == DialogResult.OK)
出现
在可以调用 OLE 之前,必须将当前线程设置为单线程单元(STA)模式。请确保您的 Main 函数带有 STAThreadAttribute 标记。 只有将调试器附加到该进程才会引发此异常。

解决方案 »

  1.   

    多线程,要在main上指定多线程把[STAThread]换成[MTAThread]
      

  2.   

    在多线程中执行处理时,不可以在线程中调用UI操作,象你的例子,可以在外部传入路径参数,在多线程中更新主线程中的UI,要在主线程中调用Invoke.
      

  3.   

    象你这个处理,可以将线程处理定成一个类,如:
    class ThreadProces
    {
     string strPath;//待处理的路径
     Thread m_thread;
     public ThreadProcess( string path )
     {
        strPath = path;
        m_thread = new Thread(new ThreadStart(Run) );
        m_thread.Start();
     } private void Run( object o )
     {
       处理搜索,引发搜索处理事件信息,供UI层显示调用   
     }}