代码
  public Form1()
        {
            InitializeComponent();
        }
        
        public delegate void dd();
        private void f()
        {
            while (true)
            {
                Thread.Sleep(1000);
                Print();
            }
        }
        public void Print()
        {
            if (this.textBox1.InvokeRequired)//检查当前线程是不是控件所在线程
            {
                dd g = new dd(Print);
                this.Invoke(g);
            }
            else
            {
                if (Thread.CurrentThread.Name == "1")
                {
                    textBox1.Text += "1";
                }
                else if (Thread.CurrentThread.Name == "2")
                { textBox1.Text = "2"; }
                else 
                { textBox1.Text += "f"; }
            }
            
        }        private void Form1_Load(object sender, EventArgs e)
        {
            Thread t1 = new Thread(new ThreadStart(f));
            //ThreadStart t = new ThreadStart(f);
            //Thread t1 = new Thread(t);
            t1.Name = "1";
            t1.Start();
            t1.IsBackground = true;
            Thread t2 = new Thread(new ThreadStart(f));
            t2.Name = "2";
            t2.IsBackground = true;//设置为后台进程
            t2.Start();
        }
我发现为什么,只会输出ffffffff,难道不能让t1,t2都改变textbox的值吗,这个说到底t1,t2没什么用,求大神改一改,让运行到线程t1时输出1,线程t2时输出2

解决方案 »

  1.   

    看错了。还是稍微有点靠谱的。但是问题在于,这代码当然只能输出f,因为
    if (Thread.CurrentThread.Name == "1")或者
    if (Thread.CurrentThread.Name == "2")根本就不可能成立,当当前线程不是主线程的时候
    if (this.textBox1.InvokeRequired)肯定是true。
      

  2.   

    换言之,你知道用invoke这是你唯一靠谱的地方,但是invoke的用处就是让主线程来执行。
      

  3.   

    本帖最后由 caozhy 于 2012-10-09 12:28:40 编辑