转---c#,从不是创建它的线程访问

时间:2022-07-26 18:22:41

转载地址:http://blog.csdn.net/yuzelong36/article/details/4028768

//新建一个代理

        private delegate void txtHandeler(object obj);

        //新建一个线程
        private void btnNewThread_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(manyThreads);
            thread.Start(sender);
        }

        //具体赋值方法
        private void manyThreads(object obj)
        {
            //(1)方法(1)错误,如果不用(2)方法不能给textBox赋值,因为不是从创建它的线程访问它;
            //textBox1.Text = "adfasfd";

            //(2)方法(2)正确,用一个代理访问它,并invoke
            txtHandeler txthandler = new txtHandeler(evaluateTxt);
            textBox1.Invoke(txthandler, new object[] { obj });
        }
        private void evaluateTxt(object obj)
        {
            textBox1.Text = "new world!";
        }