delegate.BeginInvoke跟control.invoke ┅

來源:互聯網
上載者:User
                                Return          Work Thread

Control.Invoke                  完成工作        強制於 UI Thread
Control.BeginInvoke             立即            強制於 UI Thread
[delegate].Invoke               完成工作        Call Invoke 的 Thread
[delegate].BeginInvoke          立即            新的背景 Thread

-------------------------------------------------------------------------

1、Button = button1
2、TextBox = textBox1 (請設 multiline)

然後把 button1 的 OnClick 連到下面 source code 裡的 button1_Click

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

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public delegate void testDelegate(string text);

        public Form1()
        {
            InitializeComponent();
        }

        private void UpdateTextBox(string text)
        {
            textBox1.Text += string.Format("{0}{1}", text, Environment.NewLine);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            testDelegate t = new testDelegate(UpdateTextBox);
            this.Invoke(t, "Control.Invoke");
            this.BeginInvoke(t, "Control.BeginInvoke");

            t.Invoke("[delegate].Invoke");
            // 建議先 comment 掉下面這行跑一次,再拿掉 comment 跑一次
            // 下面這行就是所謂的 [delegate].BeginInvoke
            // 但是當你 call 了之後,在 UpdateTextBox 裡會出現 exception
            // 因為它使用新的背景 thread 來跑這個工作
            // 但是 Form 不允許由別的 thread 來 access Form 上的任何 control
            // t.BeginInvoke("[delegate].BeginInvoke", null, null);
        }
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.