zoukankan      html  css  js  c++  java
  • 异步使用委托delegate --- BeginInvoke和EndInvoke方法

    当我们定义一个委托的时候,一般语言运行时会自动帮委托定义BeginInvoke 和 EndInvoke两个方法,这两个方法的作用是可以异步调用委托。

    方法BeginInvoke有两个参数:

    • AsyncCallBack:回调函数,是一个委托,没有返回值,可以传一个参数,参数类型是object;
    • object AsyncState :回调函数的参数。

    BeginInvoke的返回值是IAsyncResult,

    方法EndInvoke需要的参数是BeginInvoke的返回值IAsyncResult.

    举例如下:

        class AsyncStateTest
        {
            private delegate void DelegateTest();
    
            public static void TestAsyncState()
            {
                DelegateTest delegateTest = new DelegateTest(delegateImpl);
                Console.WriteLine("Main method begin delegateTest");
                IAsyncResult asyncResult = delegateTest.BeginInvoke(new AsyncCallback(CallBack), "I am AsyncState(*_*)");
                //delegateTest.EndInvoke(asyncResult);
                Console.WriteLine("Main method end delegateTest");
                delegateTest.EndInvoke(asyncResult);
                Console.WriteLine("Main method continue");
            }
    
            private static void CallBack(IAsyncResult asyncResult)
            {
                object state = asyncResult.AsyncState;
                Console.WriteLine(state.ToString());
            }
    
            private static void delegateImpl()
            {
                Console.WriteLine("I am DelegateTest Impl");
            }
        }

    运行结果:

    Main method begin delegateTest
    Main method end delegateTest
    I am DelegateTest Impl
    Main method continue
    I am AsyncState(*_*)

    可以看到,主线程的输出先于委托方法的输出,证明该方法被异步执行了。另外EndInvoke方法的作用是阻塞线程(调用委托的主线程),使之等到委托的方法执行完毕(但是不会等到委托的回调函数执行完毕),上面的代码换一下EndInvoke方法的位置可以看到结果。

  • 相关阅读:
    关于在MAC上进行 LARAVEL 环境 Homestead 安装过程记录
    js 贷款计算器
    js 实现阶乘
    js 两点间距离函数
    composer Your requirements could not be resolved to an installable set of packages
    vue 项目优化记录 持续更新...
    vue 项目打包
    vue 真机调试页面出现空白
    vue 真机调试
    谈谈-Android状态栏的编辑
  • 原文地址:https://www.cnblogs.com/heisehenbai/p/10100278.html
Copyright © 2011-2022 走看看