.net 4.0的Task已经让我们可以非常简单地使用多线程,并且可以有返回值,也可以支持线程的取消等操作,可谓已经很强大了。但.net 4.5为我们带来了async&await,使得实现多线程的写法更简单,更优美,更符合线性思维。
下面通过一个例子来演示通过Task和async&await分别如何实现,并且最后还附上代码执行顺序图。
使用Task实现
如下代码:
1 #region 使用Task实现 2 static void TestByTask() 3 { 4 Console.WriteLine("main thread start,current thread id:" + Thread.CurrentThread.ManagedThreadId); 5 var task = Task.Factory.StartNew(() => 6 { 7 return GetNameByTask(); 8 }); 9 Console.WriteLine("get another thread result,result:" + task.Result);10 Console.WriteLine("main thread completed!");11 }12 13 static string GetNameByTask()14 {15 Console.WriteLine("another thread start,current thread id:" + Thread.CurrentThread.ManagedThreadId);16 return "mcgrady";17 } 18 #endregion
输出结果:
使用async&await实现
假如使用async&await如何实现呢,如下代码:
1 #region 使用async&await实现 2 static async void TestByAsyncAwait() 3 { 4 Console.WriteLine("main thread start,current thread id:" + Thread.CurrentThread.ManagedThreadId); 5 var name = GetNameByAsyncAwait(); 6 7 Console.WriteLine(string.Format("get another thread result,result:{0}", await name)); 8 Console.WriteLine("main thread completed!"); 9 }10 11 static async TaskGetNameByAsyncAwait()12 {13 return await Task.Factory.StartNew (() =>14 {15 Console.WriteLine("another thread start,current thread id:" + Thread.CurrentThread.ManagedThreadId);16 return "mcgrady";17 });18 } 19 #endregion
输出结果:
输出结果跟使用Task相同。
代码执行流程如下图:
完整代码:
1 namespace ConsoleApplication25 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 //1,使用task实现 8 //TestByTask(); 9 10 //2,使用async&await实现11 TestByAsyncAwait();12 13 Console.ReadKey();14 }15 16 #region 使用Task实现17 static void TestByTask()18 {19 Console.WriteLine("main thread start,current thread id:" + Thread.CurrentThread.ManagedThreadId);20 var task = Task.Factory.StartNew(() =>21 {22 return GetNameByTask();23 });24 Console.WriteLine("get another thread result,result:" + task.Result);25 Console.WriteLine("main thread completed!");26 }27 28 static string GetNameByTask()29 {30 Console.WriteLine("another thread start,current thread id:" + Thread.CurrentThread.ManagedThreadId);31 return "mcgrady";32 } 33 #endregion34 35 #region 使用async&await实现36 static async void TestByAsyncAwait()37 {38 Console.WriteLine("main thread start,current thread id:" + Thread.CurrentThread.ManagedThreadId);39 var name = GetNameByAsyncAwait();40 41 Console.WriteLine(string.Format("get another thread result,result:{0}", await name));42 Console.WriteLine("main thread completed!");43 }44 45 static async Task GetNameByAsyncAwait()46 {47 return await Task.Factory.StartNew (() =>48 {49 Console.WriteLine("another thread start,current thread id:" + Thread.CurrentThread.ManagedThreadId);50 return "mcgrady";51 });52 } 53 #endregion54 }55 }