Synchronization: If you call a method in your code, you must wait until all of the code in the method has finished executing before you can return to the original place to execute the next line of code.
Async: Executes the next line of code if you do not wait for the calling method to finish executing.
1.0 Synchronization Examples:
1 class Program2 {3 Private Static intCalculate (intAintb)4 {5Console.WriteLine ("1. Start counting! ");6 7System.Threading.Thread.Sleep ( +*3);//If the calculation takes 3 seconds8 9 intc = A +b;Ten OneConsole.WriteLine ("2. Calculation complete, result: {0}+{1}={2}", A, b, c); A - returnC; - } the - Static voidMain (string[] args) - { -Console.WriteLine ("---------The start of the program run----------"); + -Calculate (1,2); + AConsole.WriteLine ("---------The end of the program run----------"); at - Console.readkey (); - } -}
1.1 Operation Result:
2.0 using asynchronous calls instead
1 Static voidMain (string[] args)2 {3Console.WriteLine ("-----------The start of the program run----------");4 5func<int,int,int> action = Calculate;//declaring a delegate6 7IAsyncResult ret = action. BeginInvoke (1,2,NULL,NULL);8 9Console.WriteLine ("1. I do not participate in the calculation, go first ah! ");Ten One intAmount =action. EndInvoke (ret); A -Console.WriteLine ("-----------The end of the program run----------"); - the Console.readkey (); -}
2.1 Operation Result:
2.2 In order to improve the experience of the program, we can calculate the time, every second, print a point "." The overall code is changed to the following:
1 Private Static intCalculate (intAintb)2 {3System.Threading.Thread.Sleep ( +*Ten);//If the calculation takes 3 seconds4 5 intc = A +b;6 7Console.WriteLine ("\ r \ n calculation complete, result: {0}+{1}={2}", A, b, c);8 9 returnC;Ten } One A Static voidMain (string[] args) - { -Console.WriteLine ("-----------The start of the program run----------"); the -func<int,int,int> action = Calculate;//declaring a delegate - -IAsyncResult ret = action. BeginInvoke (1,2,NULL,NULL); + -Console.WriteLine ("I do not participate in the calculation, go first ah! "); + AConsole.WriteLine ("efforts are being made to calculate:"); at while(Ret. IsCompleted = =false) - { -Console.Write ("."); -System.Threading.Thread.Sleep ( +); - } - in intAmount =action. EndInvoke (ret); - toConsole.WriteLine ("-----------The end of the program run----------"); + - Console.readkey (); the}
2.3 Operation Result:
Asynchronous programming implemented by delegates in C #