大家好,又见面了,我是你们的朋友全栈君。
原地址路径:https://www.cnblogs.com/personblog/archive/2019/10/09/11640801.html
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://javaforall.cn/161824.html原文链接:https://javaforall.cn