.NET ez 2011-11-29
在 .Net 3.5 之前所提供的 Collections 不是 thread-safe 的,必須使用.Net 4.0 ,System.Collections.Concurrent Namespace 下的泛型。
錯誤寫法
List<string> testData = new List<string>(); List<string> resultData = new List<string>(); Parallel.For(0, testData.Count() - 1, (i, loopState) => { resultData.Add(testData[i]); });
正確寫法
List<string> testData = new List<string>(); ConcurrentStack<string> resultData = new ConcurrentStack<string>(); Parallel.For(0, testData.Count() - 1, (i, loopState) => { resultData.Add(testData[i]); });
用途在於防止資源競爭!
標籤: .NET
本文章網址:
https://www.ez2o.com/Blog/Post/csharp-Parallel-Mulit-Thread-ConcurrentStack
https://www.ez2o.com/Blog/Post/11
https://www.ez2o.com/Blog/Post/csharp-Parallel-Mulit-Thread-ConcurrentStack
https://www.ez2o.com/Blog/Post/11