zoukankan      html  css  js  c++  java
  • Invoke 与 BeginInvoke 应用场景

    1.委托中 Invoke , BeginInvoke 特点

    Invoke  : 同步调用 , 委托在当前线程执行

    BeginInvoke : 异步调用 , 通常使用线程池资源执行委托。

    2. UI  控件中包含 Invoke , BeginInvoke 特点

    Invoke : 在UI线程执行委托,等待执行完成返回。

    BeginInvoke : 异步在 UI 线程执行委托 ,无需等待返回。 通常执行完毕 触发 AsyncCallback , 完成回调。

    private void button1_Click(object sender, EventArgs e)
            {
                Action<string> action = new Action<string>((s) => {
                    System.Threading.Thread.Sleep(5000);
                    MessageBox.Show("sleep 5000 ms" + " IsThreadPoolThread:" + System.Threading.Thread.CurrentThread.IsThreadPoolThread + " ID:" + System.Threading.Thread.CurrentThread.ManagedThreadId);
                });
    
                //委托的同步异步调用
                //BeginInvoke 使用线程池执行委托
               // IAsyncResult result = action.BeginInvoke(null, new AsyncCallback((s) => { MessageBox.Show("执行完毕!" + s.AsyncState + " IsThreadPoolThread:" + System.Threading.Thread.CurrentThread.IsThreadPoolThread); }), "执行完成,回调传入参数!");
               ////result.AsyncWaitHandle.WaitOne();
               // action.EndInvoke(result);
               // result.AsyncWaitHandle.Close();
    
                ////Invoke 同步调用 , 默认使用当前线程
                action.Invoke("传入参数!");
                System.Threading.Thread.Sleep(1000);
                MessageBox.Show("sleep 1000 ms  ID:" + System.Threading.Thread.CurrentThread.ManagedThreadId);
    
                
                //UI 控件 Invoke 特点
                //this.InvokeRequired  判断当前线程是否是UI线程
                //this.Invoke(...)  同步在UI线程调用指定方法
                //this.BeginInvoke(...)  异步在UI 线程调用指定方法
    
         }
  • 相关阅读:
    idea 插件之 SequenceDiagram
    idea 中添加mybatis的mapper文件模板
    springBoot 中 logback配置文件详解
    Mysql show processlist、show profiles 排查问题
    input 输入框效验
    Java基础之comparator和comparable的区别以及使用
    mysql sql使用记录
    mysql 优化之索引的使用
    IDEA 中常用快捷键的使用
    form表单中method的get和post区别
  • 原文地址:https://www.cnblogs.com/a_bu/p/8074437.html
Copyright © 2011-2022 走看看