C#并行编程之数据并行

时间:2023-03-08 16:35:40
C#并行编程之数据并行

所谓的数据并行的条件是:

1、拥有大量的数据。

2、对数据的逻辑操作都是一致的。

3、数据之间没有顺序依赖。

运行并行编程可以充分的利用现在多核计算机的优势。记录代码如下:

 public class ParallerFor
{
public List<string> studentList; public ParallerFor() {
this.studentList = new List<string>();
for (int i = ; i < ; i++) {
this.studentList.Add("xiaochun"+i.ToString());
}
} public void ParallerTest() {
var sw = Stopwatch.StartNew();
foreach (string str in this.studentList) {
Console.WriteLine("this is sync "+str);
Thread.Sleep();
}
Console.WriteLine("运行时间:"+sw.Elapsed.ToString());
} public void ParallerAsyncTest() {
var sw = Stopwatch.StartNew();
Action<int> ac = (i) => { Console.WriteLine("this is async " + this.studentList[i]); Thread.Sleep(); };
Parallel.For(, this.studentList.Count,ac);//这里的0是指循环的起点
Console.WriteLine("运行时间:" + sw.Elapsed.ToString());
} public void ParallalForEachTest() {
var sw = Stopwatch.StartNew();
Action<string> ac = (str) => {
int num = int.Parse(str.Replace("xiaochun",string.Empty));
if (num > ) {
Console.WriteLine(str);
Thread.Sleep();
}
};
//限定最大并行数目
ParallelOptions op = new ParallelOptions();
op.MaxDegreeOfParallelism = ;
Parallel.ForEach(this.studentList,op,ac);
//这里没有限定最大并行数目
//Parallel.ForEach(this.studentList,ac);
} }