.NET:如何并行的从集合中返还元素?
实现代码
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Threading; 7 using System.Collections.Concurrent; 8 9 namespace CSharpStudy.ParallelStudy 10 { 11 class HowToReturnList 12 { 13 public static void Error_Test() 14 { 15 var list = Enumerable.Range(1, 1000); 16 17 var results = new List<string>(); 18 Parallel.ForEach(list, (item) => 19 { 20 results.Add("item:" + item); 21 }); 22 23 Console.WriteLine(results.Count); 24 } 25 26 public static void Lock_Test() 27 { 28 var list = Enumerable.Range(1, 1000); 29 30 var results = new List<string>(); 31 Parallel.ForEach(list, (item) => 32 { 33 lock (results) 34 { 35 results.Add("item:" + item); 36 } 37 }); 38 39 Console.WriteLine(results.Count); 40 } 41 42 public static void Concurrent_Collections_Test() 43 { 44 var list = Enumerable.Range(1, 1000); 45 46 var results = new ConcurrentQueue<string>(); 47 Parallel.ForEach(list, (item) => 48 { 49 lock (results) 50 { 51 results.Enqueue("item:" + item); 52 } 53 }); 54 55 Console.WriteLine(results.Count); 56 } 57 58 public static void Task_Test() 59 { 60 var list = Enumerable.Range(1, 1000); 61 62 var tasks = list.Select(item => 63 { 64 return Task.Run<string>(() => 65 { 66 return "item:" + item; 67 }); 68 }).ToArray(); 69 Task.WhenAll(tasks); 70 71 Console.WriteLine(tasks.Select(x => x.Result).Count()); 72 } 73 74 public static void PLinq_Test() 75 { 76 var list = Enumerable.Range(1, 1000); 77 78 var results = list.AsParallel().Select(item => "item:" + item); 79 80 Console.WriteLine(results.Count()); 81 } 82 } 83 }