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方法的位置可以看到结果。

  • 相关阅读:
    Windows API 的数据类型与 Delphi 数据类型对照表
    Delphi 编译错误信息表
    Delphi中的容器类
    Delphi 快捷键
    代码折叠
    [转]Delphi中record的使用
    [转]常用公共函数单元
    Delphi 运行时错误信息表
    C#调用Win32 的API函数User32.dll
    [转]Delphi程序启动参数的读取
  • 原文地址:https://www.cnblogs.com/heisehenbai/p/10100278.html
Copyright © 2011-2022 走看看