在这段代码中,我们新创建了一个表示公司职员信息的类Employee以及管理公司所有职员的类EmployeeList,这里为了简便,我们只是在构造函数中人为地添加了一些要处理的数据,在实际应用中,这些数据可以来自文件,也可以来自数据库。EmployeeList这就是我们需要处理的数据集合。
使用Parallel.For进行并行化
通常我们在处理大量相互独立的同类数据的时候,比如vector,list这些容器中的数据,都会用到for循环。利用for循环,我们遍历数据集中的每一个数据并进行处理。在以前的单核时代,我们要处理EmployeeList中的所有数据,通常会这样做:
// 输出函数开始执行信息
private static void Start(string strMethod)
{
start = DateTime.Now;
Console.WriteLine("{0} process started at {1}", strMethod, start);
}
// 输出函数结束执行信息,报告函数执行的时间
private static void End(string strMethod)
{
end = DateTime.Now;
TimeSpan jobTime = end.Subtract(start);
// 输出函数执行耗时
Console.WriteLine("{0} finished at {1} and took {2}",
strMethod, end, jobTime);
Console.WriteLine();
}
// 标准的for循环
private static void StandardForLoop()
{
// 输出函数开始执行
Start("StandardForLoop");
for (int i = 0; i < employeeData.Count; i++)
{
Console.WriteLine("Starting process for employee id {0}",
employeeData[i].EmployeeID);
decimal span = Employee.Process(employeeData[i]);
Console.WriteLine("Completed process for employee id {0} process took {1} seconds",
employeeData[i].EmployeeID, span);
Console.WriteLine();
}
// 输出函数结束执行
End("StandardForLoop");
}
private static void Start(string strMethod)
{
start = DateTime.Now;
Console.WriteLine("{0} process started at {1}", strMethod, start);
}
// 输出函数结束执行信息,报告函数执行的时间
private static void End(string strMethod)
{
end = DateTime.Now;
TimeSpan jobTime = end.Subtract(start);
// 输出函数执行耗时
Console.WriteLine("{0} finished at {1} and took {2}",
strMethod, end, jobTime);
Console.WriteLine();
}
// 标准的for循环
private static void StandardForLoop()
{
// 输出函数开始执行
Start("StandardForLoop");
for (int i = 0; i < employeeData.Count; i++)
{
Console.WriteLine("Starting process for employee id {0}",
employeeData[i].EmployeeID);
decimal span = Employee.Process(employeeData[i]);
Console.WriteLine("Completed process for employee id {0} process took {1} seconds",
employeeData[i].EmployeeID, span);
Console.WriteLine();
}
// 输出函数结束执行
End("StandardForLoop");
}