Invoke和BeginInvoke的区别

    技术2022-07-11  95

    1.示例代码

    public partial class Form1 : Form { private delegate void InvokeDelegate(); public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + "AAA"); Thread invokeThread = new Thread(new ThreadStart(StartMethod)); invokeThread.Start(); string a = ""; for (int i = 0; i < 3; i++) { Thread.Sleep(1000); a = a + "B"; } MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + a); } private void StartMethod() { MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + "CCC"); Console.WriteLine("CCC"); button1.Invoke(new InvokeDelegate(invokeMethod)); button1.Invoke(new InvokeDelegate(()=>MessageBox.Show("这是一个匿名委托"))); //如果是Invoke的话出现的是AC+3秒+EBD //如果是BeginInvoke的话出现的是ACD+3秒+EB //对于子线程而言Invoke同步,BeginInvoke为异步 MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + "DDD"); } private void invokeMethod() { //Thread.Sleep(3000); MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + "EEE"); } }

    2.总结

    这里分别使用Invoke和BeginInvoke做对比发现 1.如果是Invoke的话出现的是AC+3秒+EBD 2.如果是BeginInvoke的话出现的是ACD+3秒+E 3.button1.Invoke(new InvokeDelegate(()=>MessageBox.Show(“这是一个匿名委托”))); 这里的委托是一个参数不可修改,里面的参数是可以采用匿名形式的。 可以看到主线程一直执行UI刷新工作,对于子线程而言Invoke同步,BeginInvoke为异步。

    Processed: 0.013, SQL: 9