//1 For
ParallelLoopResult res2 = Parallel.For(0, arr.Length, (i)=>output[i]=arr[i]*2);
//2 ForEach
ParallelOptions options = new ParallelOptions
{
MaxDegreeOfParallelism = 4,//最大并行数量
CancellationToken = token
};
ParallelLoopResult res= Parallel.ForEach(arr, options, (p) =>
{
p = p * 2;
});
if (res.IsCompleted)
{
Console.WriteLine("循环完成");
}
else
{
Console.WriteLine("循环被取消");
}
//3 允许你并行执行多个委托。这在你需要并行执行几个独立的任务时很有用。
Parallel.Invoke(
() => Tthread(),
() => Tthread(),
() => Tthread()
);
//4 PLINQ并行LINQ 允许你在调用LINQ方法时启用并行执行。这通常通过在 ToParallel() 或使用 .AsParallel() 来启用。
output = arr.AsParallel().AsOrdered().Select(x =>
{
return x * 2;
}).ToArray();