Parallel.ForEach相对于foreach是多线程,并行操作;foreach是单线程品德操作。
static void Main(string[] args) { Console.WriteLine("Hello World!"); List<UserInfo> lst = new List<UserInfo> { }; UserInfo[] array = new UserInfo[] {}; for (int i = 1; i <= 10; i++) { lst.Add(new UserInfo { Age=new Random().Next(1,10),Id=Guid.NewGuid()}); } foreach (var item in lst) { Console.WriteLine("循环更改前的值:"+item.Id+","+item.Age+","+item.Uname); } array = lst.ToArray(); //注意Parallel.ForEach 里面传的是数组, MaxDegreeOfParallelism = Environment.ProcessorCount指的是系统有几个cpu就使用几个cpu ParallelLoopResult result = Parallel.ForEach(array, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount },item => { item.Uname = "张" + item.Age; }); foreach (var item in array) { Console.WriteLine("循环更改后的值:" + item.Id + "," + item.Age + "," + item.Uname); } Console.ReadKey(); }
public class UserInfo { public Guid Id { get; set; } public Int32 Age { get; set; } public String Uname { get; set; } }
原文地址:https://www.cnblogs.com/personblog/p/11640801.html
时间: 2024-10-19 02:34:48