Parallel.ForEach 使用多线遍历循环
程序员文章站
2022-06-29 11:23:24
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; } }