1. 程式人生 > >非同步使用委託delegate --- BeginInvoke和EndInvoke方法

非同步使用委託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方法的位置可以看到結果。