日期:2014-05-18  浏览次数:20846 次

c#窗体多线程无效
C# code

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Text = "a";
            textBox2.Text = "b";

            Thread t1 = new Thread(new ThreadStart(Thread1));
            t1.Start();

            Thread t2 = new Thread(new ThreadStart(Thread2));
            t2.Start();

        }


        public void Thread1() {
            if (this.InvokeRequired) {
                this.Invoke(new Action(Thread1));
            }
            else
            {
                int i = 0;
                for (i = 0; i < 100; i++)
                {
                    textBox1.Text = "a" + i.ToString();
                    Thread.Sleep(0);
                    //Application.DoEvents();
                }
            }
        }


        public void Thread2()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(Thread2));
            }
            else
            {
                int i = 0;
                for (i = 0; i < 100; i++)
                {
                    textBox2.Text = "b" + i.ToString();
                    Thread.Sleep(10);
                    //Application.DoEvents();
                }
            }
        }


程序可以运行,结果是当2运行完,1和2一起显示。请问如何做到他俩分别显示,谁运行完谁显示,不要一起显示。1和2的Thread.Sleep有区别

------解决方案--------------------
Thread1 和 Thread2 两个方法改动下
C# code
public void Thread1()
{
    int i = 0;
    for (i = 0; i < 100; i++)
    {
        this.Invoke((MethodInvoker)(() => textBox1.Text = "a" + i.ToString()));
        Thread.Sleep(10);
    }
}


public void Thread2()
{
    int i = 0;
    for (i = 0; i < 100; i++)
    {
        this.Invoke((MethodInvoker)(() => textBox2.Text = "b" + i.ToString()));
        Thread.Sleep(10);
    }
}