await + Task.Run()
using System; using System.Text; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Test { class Program { public static string DateTime_Now_ToString() { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); } private static async Task<string> GetAwaitRunString(string str) { Console.WriteLine("11GetAwaitRunString:线程Id:【{0}】是否后台线程:【{1}】是否使用线程池:【{2}】当前时间:【{3}】", Environment.CurrentManagedThreadId.ToString(), Thread.CurrentThread.IsBackground, Thread.CurrentThread.IsThreadPoolThread, DateTime.Now.ToString()); var task = await Task.Run<string>(() => { Console.WriteLine("22GetAwaitRunString:线程Id:【{0}】是否后台线程:【{1}】是否使用线程池:【{2}】当前时间:【{3}】", Environment.CurrentManagedThreadId.ToString(), Thread.CurrentThread.IsBackground, Thread.CurrentThread.IsThreadPoolThread, DateTime.Now.ToString()); return str + "," + DateTime_Now_ToString(); }); return task; //return await Task.Run<string>(() => //{ // return str + DateTime_Now_ToString(); //}); } static void Main() { Console.WriteLine("Main:线程Id:【{0}】是否后台线程:【{1}】是否使用线程池:【{2}】当前时间:【{3}】", Environment.CurrentManagedThreadId.ToString(), Thread.CurrentThread.IsBackground, Thread.CurrentThread.IsThreadPoolThread, DateTime.Now.ToString()); string result = GetAwaitRunString("abc123").Result; Console.WriteLine("结果:" + result); Console.WriteLine("\n执行完毕:" + DateTime_Now_ToString()); Console.ReadLine(); } } }
打印运行结果:
/* Main:线程Id:【9】是否后台线程:【False】是否使用线程池:【False】当前时间:【2016/9/13 21:18:44】 11GetAwaitRunString:线程Id:【9】是否后台线程:【False】是否使用线程池:【False】当前时间:【2016/9/13 21:18:44】 22GetAwaitRunString:线程Id:【10】是否后台线程:【True】是否使用线程池:【True】当前时间:【2016/9/13 21:18:44】 结果:abc123,2016-09-13 21:18:44 执行完毕:2016-09-13 21:18:44 */
小结:
async Task<string> GetAwaitRunString(string str) 方法内部是同步执行的。
直到运行到 await 关键字(内部)是异步执行的(使用后台线程池)。

浙公网安备 33010602011771号