从不是创建控件“richTextBox2”的线程访问出错

来源:互联网 发布:手机桌面时钟软件 编辑:程序博客网 时间:2024/05/17 23:05
线程间操作无效: 从不是创建控件“richTextBox2”的线程访问它,即不能从一个新的线程调用另一个线程建立的element的方法,
需要调用的的时候需要使用委托以及element的Invoke方法,即: invoke(委托(实现方法))
大致的思想就是:

//*****
      ** 新建一个线程
      ** 新建一个委托
      ** 新建一个方法,该方法开启线程装在方法
      ** 新建一个方法,该方装在于线程内
      ** 新建一个方法,线程装载的方法调用此方法,此方法开始委托,即 invoke(委托(实现方法))
//*****     

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace Invoke2
{
    public partial class Form1 : Form
    {

        private delegate void Mydelegate();
        Mydelegate  mydele ;
        ThreadStart start;

        Thread myThread;
        public Form1()
        {
            InitializeComponent();
             start = new ThreadStart(NewThread);
            mydele = new Mydelegate (Change);
        }

        private void NewThread()
        {
            button1.Invoke(mydele );
        }

        private void Change()
        {
            button1.Text = "OK";
        }

        private void button1_Click(object sender, EventArgs e)
        {
             myThread = new Thread(start);
             myThread.Start();  
        }
    }
}