Parallel.ForEach相對於foreach是多線程,並行操作;foreach是單線程品德操作。 ...
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; } }