在线程中,非主线程要如何调出另一个窗口while(!exitWhile)
{
     receiveStr = sr.ReadLine();
     
     switch(receiveStr)
     {
       case "aa":
           Form2 f = new Form2();
           f.show();
           break;
       default:
           break;
     }
}

解决方案 »

  1.   


    while(!exitWhile)
    {
         receiveStr = sr.ReadLine();
         
         switch(receiveStr)
         {
           case "aa":
               //Form2 f = new Form2();
               //f.show();
                OperateUI op = new OperateUI(operateui);
                this.BeginInvoke(op);           break;
           default:
               break;
         }
    }
    ---------------------------------------
     private delegate void OperateUI();
            private void operateui()
            {
                Form2 fm = new Form2();
                fm.Show();
            }
      

  2.   

    Form窗体就是一个控件,确切的说是容器控件。所以要在线程里访问必须保证线程安全,这里可以通过代理来解决这个问题,看例子:using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Threading;namespace WindowsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }        private delegate void MoveLabel(int val);//声明代理
            Thread td;
            bool show = true;
            private void Form1_Load(object sender, EventArgs e)
            {
                td = new Thread(new ThreadStart(ThreadFun));
                td.Start();
            }        void SetOffset(int val)
            {
                //this.label1.Location = new System.Drawing.Point(label1.Location.X + val, label1.Location.Y);
                Form2 f = new Form2();
                f.ShowDialog();
            }
            private void ThreadFun()
            {
                while (true)
                {
                    if (this.InvokeRequired && show)
                    {
                        MoveLabel d = new MoveLabel(SetOffset);
                        object[] arg = new object[] { 1 };//要传入的参数值,只是为了你看这么传递参数的
                        this.Invoke(d, arg);
                        show = !show;
                    }
                }
            }
        }
    }这个是我的一个小例子改的,关于代理更详细的例子可以看这里:
    http://download.csdn.net/source/1584578