zoukankan      html  css  js  c++  java
  • 委托的异步

    1.委托的异步使用BeginInvoke,这样程序执行时不需要等待委托的函数执行完以后再执行下一句。

    但是委托的异步如果有返回值

    1
    2
    3
    4
    5
    private delegate void invokeDelegate();
    del = new invokeDelegate(StartMethod);
    var re=   del.BeginInvoke(null, null);
    MessageBox.Show( del.EndInvoke(re));
     MessageBox.Show("f");

    这个时候就会堵塞,等待StartMethod执行完才会走到第5句,没有体现出异步的功能。

    回调函数可以解决这个问题,可以将EndInvoke放在IAsyncCallback中执行,将3,4句改为

    1
    IAsyncResult ir = id.BeginInvoke(AddComplete, null);

     并添加以下函数:

    1
    2
    3
    4
    5
    prvite void AddComplete(IAsyncResult result)
    {
          invokeDelegate handler = (invokeDelegate)((AsyncResult)result).AsyncDelegate;
          MessageBox.Show( handler.EndInvoke(result));
     }

    这样就函数便不用等待委托执行完,可以先执行第5句。

    StartMethod方法如下:

    1
    2
    3
    4
    5
    private void StartMethod()
    {
         Thread.Sleep(5000);
        MessageBox.Show("c");
     }

    委托的BeginInvoke实际上是放在threadpool中的。

    2.control的invoke和BeginInvoke都是在主线程上的所以它们都会阻塞主线程(control所在线程)。beginInvoke不会阻塞支线程,所以它只能作为支线程的异步

  • 相关阅读:
    Set Matrix Zeroes
    Summary Ranges
    Triangle
    MongoDB基本使用
    PHP Liunx 服务安全防范方案
    linux lvs 配置
    Linux下cacti的安装
    linux_nmon监控方法
    linux下rsync命令详细整理
    虚拟机安装CentOS以及SecureCRT设置【完美无错版】
  • 原文地址:https://www.cnblogs.com/paidaxing/p/3804425.html
Copyright © 2011-2022 走看看