1 using System; 2 using System.Collections.Concurrent; 3 using System.Collections.Generic; 4 using System.Threading.Tasks; 5 6 namespace Try 7 { 8 public class ParallelTest 9 { 10 public static void Test() 11 { 12 var datas = new List<int>(); 13 for (int i = 0; i < 1000; i++) 14 { 15 datas.Add(i); 16 } 17 18 PartitionByPartCount(datas,5); 19 20 PartitionByPartSize(datas,100); 21 } 22 23 private static void PartitionByPartCount<T>(IList<T> datas, int rangeCount) 24 { 25 var rangeSize = (int)Math.Ceiling(datas.Count / (double)rangeCount); 26 var partitioner = Partitioner.Create(0, datas.Count, rangeSize); 27 Parallel.ForEach(partitioner, (part, state, rangeIndex) => { 28 for (int index = part.Item1; index < part.Item2; index++) 29 { 30 Console.WriteLine($"rangeIndex:{rangeIndex},index:{index},data:{datas[index]}"); 31 } 32 }); 33 } 34 35 private static void PartitionByPartSize<T>(IList<T> datas, int rangeSize) 36 { 37 var partitioner = Partitioner.Create(0, datas.Count, rangeSize); 38 Parallel.ForEach(partitioner, (part, state, rangeIndex) => { 39 for (int index = part.Item1; index < part.Item2; index++) 40 { 41 Console.WriteLine($"rangeIndex:{rangeIndex},index:{index},data:{datas[index]}"); 42 } 43 }); 44 } 45 } 46 }