Simple Use Cases of asynchronous delegation and simple Use Cases of asynchronous Delegation
1 // define a delegate 2 static Func <int, int, string> delFunc = (a, B) => 3 {4 Console. writeLine ("delegate Thread:" + Thread. currentThread. managedThreadId); 5 return (a + B ). toString (); 6}; 7 8 static void Main (string [] args) 9 {10 Console. writeLine ("main Thread:" + Thread. currentThread. managedThreadId); 11 12 // synchronously call the delegate 13 // string str = delFunc (3, 4); // str = delFunc. invoke (3, 4); 14 15 // asynchronous call delegate (Principle: Use the thread pool thread to execute the delegate pointing method) 16 IAsyncResul T ar = delFunc. beginInvoke (3, 4, CallBackFn, "I am a callback function parameter"); // callback function and callback function parameter 17 // string result = delFunc. endInvoke (ar); // The EndInvoke method will be blocked, waiting for the end of asynchronous delegation 18 19 Console. readLine (); 20} 21 22 // After the asynchronous delegate is executed, the callback function 23 static void CallBackFn (IAsyncResult iar) 24 {25 object obj = iar. asyncState; // callback function parameter 26 27 AsyncResult ar = iar as AsyncResult; 28 Func <int, int, string> del = ar. asyncDelegate as Func <int, int, string>; 29 s Tring result = del. EndInvoke (ar); // result of the asynchronous delegate. The delegate has been executed and will not be blocked. 30 31 Console. WriteLine ("Callback Thread:" + Thread. CurrentThread. ManagedThreadId); 32}