using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace await和async { class Program { static void Main(string[] args) { //AwaitAsync(); //TaskRun(); AwaitTaskRun(); } #region await和async private static void AwaitAsync() { Say(); //由于Main不能使用async标记 Console.ReadLine(); } private async static void Say() { var t = TestAsync(); Thread.Sleep(1100); //主线程在执行一些任务 Console.WriteLine("Main Thread"); //主线程完成标记 Console.WriteLine(await t); //await 主线程等待取异步返回结果 } static async Task<string> TestAsync() { return await Task.Run(() => { Thread.Sleep(1000); //异步执行一些任务 return "Hello World"; //异步执行完成标记 }); } #endregion #region task public static void TaskRun() { Console.WriteLine("执行GetReturnResult方法前的时间:" + DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss")); var strRes = Task.Run<string>(() => { return GetReturnResult1(); }); Console.WriteLine("执行GetReturnResult方法后的时间:" + DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss")); Console.WriteLine("我是主线程,线程ID:" + Thread.CurrentThread.ManagedThreadId); Console.WriteLine(strRes.Result); Console.WriteLine("得到结果后的时间:" + DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss")); Console.ReadLine(); } static string GetReturnResult1() { Console.WriteLine("我是GetReturnResult里面的线程,线程ID:" + Thread.CurrentThread.ManagedThreadId); Thread.Sleep(2000); return "我是返回值"; } #endregion #region AwaitTaskRun /* * await:只能标记在async方法或Task对象前面;等待异步的执行结果。 * async:标记异步方法,里面有异步执行则异步,没有则为普通方法,只能返回void、Task、Task<T> */ public static void AwaitTaskRun() { Console.WriteLine("我是主线程,线程ID:{0}", Thread.CurrentThread.ManagedThreadId); TestAsync1(); Console.ReadLine(); } static async void TestAsync1() { Console.WriteLine("调用GetReturnResult()之前,线程ID:{0}。当前时间:{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss")); var name = GetReturnResult(); Console.WriteLine("调用GetReturnResult()之后,线程ID:{0}。当前时间:{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss")); Console.WriteLine("得到GetReturnResult()方法的结果:{0}。当前时间:{1}", await name, DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss")); Console.WriteLine("最后执行,线程ID:{0}。当前时间:{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss")); } static async Task<string> GetReturnResult() { Console.WriteLine("执行Task.Run之前, 线程ID:{0}", Thread.CurrentThread.ManagedThreadId); return await Task.Run(() => { Thread.Sleep(3000); Console.WriteLine("GetReturnResult()方法里面线程ID: {0}", Thread.CurrentThread.ManagedThreadId); return "我是返回值"; }); } #endregion } }
需要等待结果执行,必须所有的方法用await,调用方法的时候也需要。