C#5.0最大的新特性,莫過於Async和Parallel。
以往我們為了讓使用者介面保持相應,我們可以直接使用非同步委託或是System.Threading命名空間中的成員,但System.Threading.Tasks命名空間提供了一種更加簡潔的方法---使用Task類。Task類可以輕鬆地在次線程中調用方法,可以作為非同步委託的簡單替代品。
關於Async,可以參考MSDN的Task 類以及使用 Async 和 Await 的非同步編程(C# 和 Visual Basic),其介紹了其中的方法、屬性等,講的都比LZ要好。
下面我們實現一個非同步呼叫的例子,看看用法有什麼不同。
我想要的是:非同步執行方法,在方法執行後緊接著非同步執行另一個方法,該方法以前面的方法結果為參數
using System;using System.Threading.Tasks;//非同步執行方法,在方法執行後緊接著非同步執行另一個方法,該方法以前面的方法結果為參數namespace AsyncTask{ class result { public int number { set; get; } } class Program { static void Main(string[] args) { var result = new result { number = 4 }; var t1 = new Task(First, result);//Action var t2 = t1.ContinueWith<int>(First1);//Func var t3 = t1.ContinueWith<int>(First2); t1.Start(); Console.WriteLine(t2.Result);//t.Result Console.WriteLine(t3.Result); Console.ReadKey(); } static void First(object o) { result x = (result)o; x.number *= 2; } static int First1(Task o) { result x = (result)o.AsyncState;// return x.number * x.number; } static int First2(Task o) { result x = (result)o.AsyncState; return x.number * x.number * x.number; } }}
可以對比DebugLZQ的.NET非同步編程總結----四種實現模式,看看同樣為非同步,實現方法有什麼不同。
關於Parallel,現在雙核(多核)的電腦已經很普片,電腦有多個CPU,就能夠以並行的方式執行線程,這將大大改善應用程式的運行時效能。
總體而言,System.Threading.Tasks中的類型(以及System.Threading中的一些相互關聯類型)被稱為工作平行程式庫(Task Parallel Library,TPL)。TPL使用CLR線程池自動將應用程式的工作動態分配到可用的CPU中。TPL還處理工作分區、線程調度、狀態管理和其他低層級的細節操作。TPL中最重要的類是System.Threading.Tasks.Parallel,它提供大量的方法,能夠以並行的方式迭代資料集合(實現了IEnumberable<T>的對象)。該類支援兩個主要的靜態方法---Parallel.For()和Parallel.ForEach() (Parallel.Invoke())每個方法都有很多的重載版本。
MSDN Parallel 類、.NET Framework 中的並行編程 可以參考,以For為例
using System.Threading.Tasks;namespace ParallelFor{ class Test { static int N = 1000; static void TestMethod() { // Using a named method. Parallel.For(0, N, Method2); // Using an anonymous method. Parallel.For(0, N, delegate(int i) { // Do Work. }); // Using a lambda expression. Parallel.For(0, N, i => { // Do Work. }); } static void Method2(int i) { // Do work. } }}
ForEach、Invoke類似
Parallel.ForEach(new[] {1, 2, 3, 4, 5}, i => Console.WriteLine("{0}, Task: {1}, Thread {2}", i, Task.CurrentId, Thread.CurrentThread.ManagedThreadId));
Parallel.Invoke( BasicAction, // Param #0 - static method () => // Param #1 - lambda expression { Console.WriteLine("Method=beta, Thread={0}", Thread.CurrentThread.ManagedThreadId); }, delegate() // Param #2 - in-line delegate { Console.WriteLine("Method=gamma, Thread={0}", Thread.CurrentThread.ManagedThreadId); } );
最後:關於Parallel和Async不是LZ一篇博文就能解釋的清楚,LZ沒有實際的用過,不敢說咋滴咋滴...博文是個人的理解,難免出現紕漏,歡迎批評指正!關於學習方面,中文的書籍普遍比較滯後,針對個人的需求並非所有的英文書籍都有翻譯版,加之翻譯者個人理解及翻譯風格的原因,最終...
關於新書,公司給買了本:
書比較厚,1k來頁,英文的書籍看起來比較慢,但是看起來很舒服。