并行编程基础——并行处理
并行编程用来拆分CPU密集型任务,并将他们分发给多个线程。
并行处理
问题
假设有一个数据集合,现在需要对数据中的每个元素执行相同的操作。该操作为CPU密集型操作,会消耗一些时间。
解决方案
Parallel类型中的ForEach方法是为此类问题量身定制的。下面的示例接受一个矩阵集合,并旋转全部矩阵
void RotateMatrices(IEnumerable<Matrix> matrices,float degrees)
{
Parallel.Foreach(matrices,matrix=>matrix.Rotate(degrees));
}
在某些情况下,需要提早终止循环,比如在遇到无效值的时候:
void InvertMatrices(IEnumerable<Matrix> matrices)
{
Parallel.ForEach(matrices,(matrix,state)=>
{
if(!matrix.IsInvertible)
state.Stop();
else
matrix.Invert();
})
}
可以通过取消按钮翘CancellationTokenSource,并取消并行循环
void RotateMatrices(IEnumerable<Matrix> matrices,float degrees,CancellationToken token)
{
Parallel.ForEach(matrices,new ParallelOption{cancellationToken=token},matrix=>matrix.Rotate(degrees));
}