简体   繁体   English

并发集合中的数组等效项

[英]Equivalent of Array in Concurrent Collections

I have the following process in a Single Thread Environment : 我在单线程环境中有以下过程:

int[] ages = { 40, 30, 18, 23, 60, 24 };
for (int i = 0; i < ages.Length; i++)
{
    if (ages[i] < 21) ages[i] = 0;
}

As an example, but now I want to do this process in a Multi Thread Environment . 作为一个例子,但现在我想在多线程环境中执行此过程。 Is there a Concurrent collection simulate an array in multi threading environment? 是否有一个Concurrent集合在多线程环境中模拟一个数组?

You can try using Parallel Linq ( PLinq ) and let .Net materialize the final result as an array; 您可以尝试使用并行LINQ(PLINQ),并让净兑现最终结果为数组; in your case: 在你的情况下:

 int[] ages = { 40, 30, 18, 23, 60, 24 };

 ages = ages
   .AsParallel()
   .Select(age => age < 21 ? 0 : age)
   .ToArray(); 

The advantage of PLinq is that .Net is responsible for the inner collections choice, locking etc. If you want, say, find an average age in parallel all you have to do is to slightly edit the query: PLinq的优点是.Net负责内部集合的选择,锁定等。如果你想要,比如说,找到一个平行的平行年龄,你所要做的就是略微编辑查询:

 var averageAge = ages
   .AsParallel()
   .Average();

Closest solution is to use ConcurrentDictionary using the index as the key. 最近的解决方案是使用索引作为键来使用ConcurrentDictionary。 The hash function will be really good in this case: 在这种情况下,哈希函数将非常好:

var dict = new ConcurrentDictionary<int, int>(Enumerable.Range(0, ages.Length).ToDictionary(i => i, i => ages[i]));
Parallel.For(0, dict.Count,
    i =>
    {
        int value;
        if (dict.TryGetValue(i, out value) && value < 21)
            dict.TryUpdate(i, value, 0);
    });

Pay attention to the fact that this particular example doesn't need to use ConcurrentDictionary at all because you have no dependency between each iteration. 请注意这个特定示例根本不需要使用ConcurrentDictionary这一事实,因为您在每次迭代之间没有依赖关系。

Parallel.For(0, ages.Length,
    i =>
    {
        if (ages[i] < 21) ages[i] = 0;
    });

This code will perfectly work for your example. 此代码将完美适用于您的示例。 Next time use something more complex like the sum of the array elements. 下次使用更复杂的东西,比如数组元素的总和。

Hope this help! 希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM