public Form1() { InitializeComponent(); } private delegate void ShowMessage(); private Thread beginInvokeThread; // ShowMessage showMessage; private void button1_Click(object sender, EventArgs e) { this.richTextBox1.Text = "(1)进入按钮" + "\n"; button1.Invoke(new ShowMessage(ButtonMessage)); this.richTextBox1.Text += "(3)已经点击" + "\n"; this.richTextBox2.Text = "(1)进入按钮" + "\n"; button1.BeginInvoke(new ShowMessage(ButtonMesage1)); this.richTextBox2.Text += "(3)已经点击" + "\n"; this.richTextBox3.Text = "(1)进入按钮" + "\n"; beginInvokeThread = new Thread(new ThreadStart(ButtonMesage3)); beginInvokeThread.Start(); this.richTextBox3.Text += "(3)已经点击" + "\n"; } private void ButtonMessage() { this.richTextBox1.Invoke(new Action(() => { this.richTextBox1.Text += "(2)点击按钮" + "\n"; this.button1.BackColor = Color.Green; this.button1.Text = "已经点击"+"\n"; })); } private void ButtonMesage1() { this.BeginInvoke(new Action(() => { this.richTextBox2.Text += "(2)点击按钮" + "\n"; })); } private void ButtonMesage3() { richTextBox3.Invoke(new Action(() => { this.richTextBox3.Text += "(2)已经点击" + "\n"; })); richTextBox3.BeginInvoke(new ShowMessage(BeginInvokeMethod)); richTextBox3.Invoke(new Action(() => { this.richTextBox3.Text += "(4)已经点击" + "\n"; })); } private void BeginInvokeMethod() { this.richTextBox3.Text += "(5)已经点击" + "\n"; }
运行结果:
这个实例说明了invoke,begininvoke的区别,以及在跨线程修改控件属性的应用;