C # asynchronous callback function
Using System; using System. collections. generic; using System. linq; using System. text; namespace ComprehensiveTest.com {public class AsyCallEx112 {// define a delegate for performing addition public delegate int sum (int a, int B); public class number {public int m = 4; public int numberAdd (int a, int B) {int c = a + B; return c ;}// defines an and. The callback function public void CallbackMothed2 (IAsyncResult ar2) {sum s = (sum) ar2.AsyncState; int number = s. endInvoke (ar2); m = number; Console. writeLine ("obtained M Value: {0}", m );}}}}
Using System; using System. collections. generic; using System. linq; using System. text; namespace ComprehensiveTest.com {public class AsyCallEx113 {// define a delegate public delegate void AsyncEventHanlder (); public class Class1 {public void Event1 () {Console. writeLine ("Event1 start"); System. threading. thread. sleep (1, 2000); Console. writeLine ("Event1 end");} public void Event2 () {Console. writeLine ("Event2 start"); int I = 1; while (I <100) {I = I + 1; Console. writeLine ("Event2" + I. toString ();} Console. writeLine ("Event2 end");} public void CallbackMethod (IAsyncResult ar) {(AsyncEventHanlder) ar. asyncState ). endInvoke (ar );}}}}
Using System; using System. collections. generic; using System. linq; using System. text; using ComprehensiveTest.com; namespace ComprehensiveTest {class Program {static void Main (string [] args) {// 112 // AsyCallEx112.number num = new AsyCallEx112.number (); // AsyCallEx112.sum numberadd = new AsyCallEx112.sum (num. numberAdd); // AsyncCallback numberBack = new AsyncCallback (num. callbackMothed2); // numberadd. beginInvoke (21, 12, numberBack, numberadd); // Console. writeLine ("Result:"); // Console. writeLine (num. m); // 113 long start = 0; long end = 0; AsyCallEx113.Class1 c = new AsyCallEx113.Class1 (); Console. writeLine ("ready"); start = DateTime. now. ticks; AsyCallEx113.AsyncEventHanlder asy = new AsyCallEx113.AsyncEventHanlder (c. event1); // IAsyncResult ia = asy. beginInvoke (null, null); IAsyncResult ia = asy. beginInvoke (new AsyncCallback (c. callbackMethod), asy); ia. asyncWaitHandle. waitOne (); c. event2 (); end = DateTime. now. ticks; Console. writeLine ("time scale difference =" + Convert. toString (end-start); Console. readLine ();}}}