System.Threading.Tasks,在該命名空間下Task是主類,表示一個類的異步的併發的操做,建立並行代碼的時候不必定要直接使用Task類,在某些狀況下能夠直接使用Parallel靜態類(System.Threading.Tasks.Parallel)下所提供的方法進行並行開發,而不用底層的Task實例。
並行處理沒法保證順序,不須要考慮任務和線程的問題,執行效率加快,固然也不是絕對的,任務的開銷大小對並行任務有影響,若是任務很小,那麼因爲並行管理的附加開銷(任務分配,調度,同步等成本),可能並行執行並非優化方案。例如:循環打印10000個數字,for的循環比Parallel.For快html
提供對並行循環和區域的支持。在Parallel下面有三個經常使用的方法invoke,For和ForEach。數組
Stopwatch stopWatch = new Stopwatch(); List<int> sourceList = new List<int>(); for (int i = 0; i <= 10000; i++) { sourceList.Add(i); } stopWatch.Reset(); stopWatch.Start(); List<int> resultList = new List<int>(); foreach (int option in sourceList) { Thread.Sleep(1); resultList.Add(option); } stopWatch.Stop(); Console.WriteLine("正常運行:" + stopWatch.ElapsedMilliseconds + " ms."); stopWatch.Reset(); stopWatch.Start(); ConcurrentBag<int> concurrentBagList = new ConcurrentBag<int>(); ParallelOptions options = new ParallelOptions(); options.MaxDegreeOfParallelism = 4; Parallel.ForEach(sourceList, options, (item) => { Thread.Sleep(1); concurrentBagList.Add(item); }); stopWatch.Stop(); Console.WriteLine("並行運行:" + stopWatch.ElapsedMilliseconds + " ms.");
上面的例子,若是把Thread.Sleep(1),去掉能夠發現,foreach比Parallel.ForEach快,因此任務的開銷很重要。ConcurrentBag若是換成List能夠發現,list中的數據不夠。List集合,數組Int[],String[] ……,Dictory字典等等。可是這些列表、集合和數組的線程都不是安全的,不能接受併發請求。微軟也提供了線程安全的類Concurrent安全
命名空間提供多個線程安全集合類。當有多個線程併發訪問集合時,應使用這些類代替 System.Collections 和 System.Collections.Generic 命名空間中的對應類型。多線程
BlockingCollection<T> 爲實現 IProducerConsumerCollection<T> 的線程安全集合提供阻塞和限制功能。
ConcurrentBag<T> 表示對象的線程安全的無序集合。能夠用來替換List<T>
ConcurrentDictionary<TKey, TValue> 表示可由多個線程同時訪問的鍵值對的線程安全集合。Dictionary<TKey, TValue>
ConcurrentQueue<T> 表示線程安全的先進先出 (FIFO) 集合。Queue<T>
ConcurrentStack<T> 表示線程安全的後進先出 (LIFO) 集合。Stack<T>併發
並行中的多線程異步
await list.ParallelForEachAsync(async l => { ....... });
1. C#中await/async閒說async
2. .NET中並行開發優化優化
3. C# Task.Run 和 Task.Factory.StartNew 區別spa
4. C#中多線程的並行處理pwa
5. C#中多線程中變量研究