Parallel.ForEach相对于foreach是多线程,并行操作;foreach是单线程品德操作。
1 static void Main(string[] args) 2 { 3 Console.WriteLine("Hello World!"); 4 List<UserInfo> lst = new List<UserInfo> { }; 5 UserInfo[] array = new UserInfo[] {}; 6 for (int i = 1; i <= 10; i++) 7 { 8 lst.Add(new UserInfo { Age=new Random().Next(1,10),Id=Guid.NewGuid()}); 9 } 10 foreach (var item in lst) 11 { 12 Console.WriteLine("循环更改前的值:"+item.Id+","+item.Age+","+item.Uname); 13 } 14 array = lst.ToArray(); 15 //注意Parallel.ForEach 里面传的是数组, MaxDegreeOfParallelism = Environment.ProcessorCount指的是系统有几个cpu就使用几个cpu 16 ParallelLoopResult result = Parallel.ForEach(array, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount },item => 17 { 18 item.Uname = "张" + item.Age; 19 20 }); 21 foreach (var item in array) 22 { 23 Console.WriteLine("循环更改后的值:" + item.Id + "," + item.Age + "," + item.Uname); 24 } 25 Console.ReadKey(); 26 }
1 public class UserInfo 2 { 3 public Guid Id { get; set; } 4 5 public Int32 Age { get; set; } 6 7 public String Uname { get; set; } 8 }