我现在开始学习TPL。我在这个视频中看到了一个使用TPL的生产者/消费者模型简单版。
感谢大家提前阅读!
问题是:
以下代码:
BlockingCollection<Double> bc = new BlockingCollection<Double>(100);
IEnumerable<Double> d = bc.GetConsumingEnumerable();
返回一个可以使用foreach进行迭代(并自动消耗)的 IEnumerable<Double>
:
foreach (var item in d)
{
// do anything with item
// in the end of this foreach,
// will there be any items left in d or bc? Why?
}
我的问题是:
- 如果我从
d
获取IEnumerator<Double> dEnum = d.GetEnumerator()
(例如用while
循环遍历d
),那么d.MoveNext()
也会消耗列表吗?(我的答案是:不会,因为dEnum
并没有与d
相关联,如果你知道我的意思的话。所以它将消耗dEnum
,但不是d
,甚至也不是bc
) - 我可以以其他方式循环遍历
bc
(或d
)而不是使用foreach
循环并消耗项吗?(使用while
循环比foreach
循环快得多,我担心在科学计算问题中出现性能问题) BlockingCollection<T>
类型中的“消耗”是什么意思?
例如,代码:
IEnumerator<Double> dEnum = d.GetEnumerator();
while (dEnum.MoveNext())
{
// do the same with dEnum.Current as
// I would with item in the foreach above...
}
感谢大家提前阅读!
foreach
会有性能问题? - Reed Copseywhile
循环、for
循环和foreach
循环完成任务所需的时间... 最终,while
循环明显更快... - Girardi