using System; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { // static async Task Main(string[] args) { //等待执行完成 var result = await Task.Run(() => { Console.WriteLine("进入子线程main执行4秒"); for (int i = 1; i <= 2; i++) { Console.WriteLine("子线程main" +"+"+ i); Thread.Sleep(2000); } Console.WriteLine("子线程main等待4秒完成返回!"); return "子线程main返回值"; }); Console.WriteLine("进入主线程main方法内!"); for (int i = 1; i <= 2; i++) { Console.WriteLine("主线程main" + "+" + i); Thread.Sleep(2000); } //不需要等待 Task1(); Task3(); Console.WriteLine("进入主线程main方法内!"); //等待 await Task2(); Console.WriteLine("进入主线程main方法内!"); Console.WriteLine(result); Console.ReadLine(); } private static async Task Task1() { Console.WriteLine("进入到了Task1方法内"); var result = await Task.Run(() => { Console.WriteLine("进入子线程task1执行5秒"); for (int i = 1; i <= 5; i++) { Console.WriteLine("task1"+ "+" + i); Thread.Sleep(1000); } Console.WriteLine("task1子线程返回!"); return "task1 5秒后的返回值"; } ); //主线程 Console.WriteLine("进入task1内"); Console.WriteLine(result); } private static async Task Task2() { Console.WriteLine("进入到了Task2方法内"); var result = await Task.Run(() => { Console.WriteLine("进入子线程task2执行10秒"); for (int i = 1; i <= 10; i++) { Console.WriteLine("task2" + "+" + i); Thread.Sleep(1000); } Console.WriteLine("task2子线程返回!"); return "task2 10秒后的返回值"; } ); Console.WriteLine("进入tast2内"); Console.WriteLine(result); } private static async Task Task3() { Console.WriteLine("进入到了Task3方法内"); for (int i = 1; i <= 10; i++) { Console.WriteLine("task3" + "+" + i); Thread.Sleep(1000); } } } }