c# - C#中并行运行循环需要什么条件?

标签 c# linq loops parallel-processing requirements

我有这样一段代码:

foreach (var elem in coll.AsParallel())
{
   ... // some *local* computation
   cache.Add(elem,computation_outcome);
}

其中cacheConcurrentDictionaryAdd是扩展方法,它包装TryAdd并在失败时抛出异常。

它有效。唯一的问题是,它不能并行运行。

问题——并行运行循环有什么要求?

我知道强制并行模式,但我只是询问并行执行的要求。

最佳答案

AsParallel() 用于 LINQ 查询。它不会使正常的 foreach() 并行运行。

你应该使用类似的东西:

Parallel.ForEach (coll, elem => 
{
   ... // some *local* computation
   cache.Add(elem,computation_outcome);
} );

关于c# - C#中并行运行循环需要什么条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10052841/

相关文章:

c# - POCO 和实用方法

c# - MongoDB Linq 驱动程序转换异常

C# 检查用户输入的特定文件名并打开文件

c# - 具有匿名类型的 linq 表达式中的 TryGetValue()

r - 在多个列上嵌套 if else 语句

c# - 使用 FileShare.Delete 会导致 UnauthorizedAccessException 吗?

c# - 列表引用问题c#

c# - Azure 表 : How to write a range query to filter on partition key

java - 在 Java 中输入无效后重新提示用户

python - 如何创建任意数量的嵌套循环?