行远-自迩

导航

委托在窗体中应用<4>

1.Control的Invoke和BeginInvoke与委托的Invoke和BeginInvoke是2个概念,不能混淆
2.Control的Invoke和BeginInvoke,他们的形参是delegate,委托的方法是在Control的线程上执行(即UI线程)
以上第一点暂时没有看懂!
直接上例子:
 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的区别,以及在跨线程修改控件属性的应用;

 

posted on 2020-06-10 13:54  行远-自迩  阅读(224)  评论(0编辑  收藏  举报