WPF Invoke与BeginInvoke的区别

时间:2023-03-09 20:02:10
WPF Invoke与BeginInvoke的区别
  • Control.Invoke 方法 (Delegate) :在拥有此控件的基础窗口句柄的线程上执行指定的委托。
  • Control.BeginInvoke 方法 (Delegate) :在创建控件的基础句柄所在线程上异步执行指定委托。

    就是一个是同步的一个是异步的,也就是一个需要等待一个不需要等待

//这个输出123
private void button1_Click(object sender, RoutedEventArgs e) {
textblock.Text += "";
this.Dispatcher.Invoke(new InvokeDelegate(Test));
textblock.Text += "";
} private void Test() {
textblock.Text += "";
} private delegate void InvokeDelegate(); //这个输出132
private void button1_Click(object sender, RoutedEventArgs e) {
textblock.Text += "";
this.Dispatcher.BeginInvoke(new InvokeDelegate(Test));
textblock.Text += "";
} private void Test() {
textblock.Text += "";
}

Invoke是线程中比较重要的一个东西,在多线程的编程中,平常在更新界面的时候,可以用UI线程去做来减轻工作线程的负担。比如下面这样放在线程中:

private void button1_Click(object sender, RoutedEventArgs e) {
Thread invokeThread = new Thread(new ThreadStart(Method));
invokeThread.Start();
//...运算代码
} private void Method(){
this.Dispatcher.BeginInvoke(new InvokeDelegate(Test));
} private void Test() {
textblock.Text += "";
} private delegate void InvokeDelegate();

简单写法如下:

private void button_Click(object sender, RoutedEventArgs e) {
this.Dispatcher.BeginInvoke(new Action(() => { this.textblock.Text += ""; }));
}