原地址路径: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://bianchenghao.cn/35568.html