zoukankan      html  css  js  c++  java
  • WPF Invoke与BeginInvoke的区别

    • Control.Invoke 方法 (Delegate) :在拥有此控件的基础窗口句柄的线程上执行指定的委托。
    • Control.BeginInvoke 方法 (Delegate) :在创建控件的基础句柄所在线程上异步执行指定委托。

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

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

    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 += "123";
            }
    
            private delegate void InvokeDelegate();

    简单写法如下:

    private void button_Click(object sender, RoutedEventArgs e) {
                this.Dispatcher.BeginInvoke(new Action(() => { this.textblock.Text += "123"; }));
            }
  • 相关阅读:
    零售数据框架
    API安全Checklist
    高级区块链工程师评定
    软件项目复杂性
    e-Commerce电商参考云架构
    面试中的学习能力判断
    SpringCloud微服务架构案例-共享服务中心
    Software Architecture and High Level Design软件架构与概要设计
    基于Istio的ServiceMesh
    a store with that domain name already exists怎么解决
  • 原文地址:https://www.cnblogs.com/zyj649261718/p/8317254.html
Copyright © 2011-2022 走看看