Parallel.For的用法 [英] Usage of Parallel.For
本文介绍了Parallel.For的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使下面的代码没有锁而平行
How can I make the code below parallel, without locks
List l = new List();
foreach (var item in sourceCollection)
{
L.Add(Process(item));
}
我更喜欢c#3.5的答案,但4.0也可以
I prefer answers for c# 3.5, but 4.0 will be also ok
推荐答案
下面是一个示例,该示例采用一系列数字,对每个数字并行执行一些代价高昂的运算,然后汇总结果(不并行). /p>
Here's an example of taking a sequence of numbers, performing some costly operation on each of them in parallel, and then aggregating the result (not in parallel).
int[] numbers = { 1, 1, 2, 3, 5, 8, 13 };
int[] squaredNumbers = new int[numbers.Length];
Parallel.For(0, numbers.Length, i => squaredNumbers[i] = (int)Math.Pow(numbers[i], 2));
int sum = squaredNumbers.Sum();
请小心在委托中执行的操作中的线程安全性.
Just be careful about thread safety in the operation you perform in the delegate.
这篇关于Parallel.For的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文