Asynchronous execution
static void the Main ( String [] args) { Console.WriteLine ( " ------- main thread start ------- " ); the Task < int > = Task GetStrLengthAsync (); Console.WriteLine ( " the main thread to continue " ); Console.WriteLine ( " Task return value " + task.Result); Console.WriteLine ( " ------- main thread ends ------- " ); Console. ReadKey (); } static the async the Task <int > GetStrLengthAsync () { Console.WriteLine ( " GetStrLengthAsync method to begin " ); // string type returned here <string> is, instead of the Task <string> String STR = the await the GetString (); Console.WriteLine ( " GetStrLengthAsync method has finished executing " ); return str.length; } static the Task < String > the GetString () { // Console.WriteLine ( "begin the GetString method") return the Task < String > .Run (() => { The Thread.Sleep ( 2000 ); Console.WriteLine ( " the GetString return value " ); return " the GetString return value " ; }); }
2 Comparison with asynchronous callback
asynchronous
static void Main(string[] args) { for (int i = 0; i < 100; i++) { test(i); } Console.ReadKey(); } static private void test(int i) { Task<int> task = GetStrLengthAsync(i); } static async Task<int> GetStrLengthAsync(int i) { Console.WriteLine(i); string str = await GetString(i); Console.WriteLine($"结束{i}"); return str.Length; } static Task<string> GetString(int i) { //Console.WriteLine("GetString方法开始执行") return Task<string>.Run(() => { Thread.Sleep(10000); Console.WriteLine($"耗时操作{i}"); return " The GetString return value " ; }); }
Callback
private delegate void AddHandler(int i); static void Main(string[] args) { for (int i = 0; i < 100; i++) { test2(i); } Console.ReadKey(); } static private void test2(int i) { AddHandler addHandler = new AddHandler(test3); addHandler.BeginInvoke(i,null,null); } static private void test3(int i) { Console.WriteLine(i); test4(i); Console.WriteLine($"结束{i}"); } static private void test4(int i) { Thread.Sleep(10000); Console.WriteLine($"耗时操作{i}"); }