1

我有电话簿中的条目:姓名+地址。来源在一个网站上,计数超过 1K 条记录。

问题是:

我如何使用/ ConcurrentDictionary实现ParallelForeach

我还不如问它会更好地执行:

ConcurrentDictionary&ParallelForeach

对比

Dictionary&foreach

由于名称不允许重复作为键,而且我认为我理解正确,只有当键不存在时才ConcurrentDictionary具有自己的 add() 内置函数。TryAdd所以不允许添加已经处理好的重复键的问题,所以从那时起我可以清楚地看到平衡正在转向ConcurrentDictionary而不是标准顺序Dictionary

那么如何从任何给定的数据源添加名称和地址并通过 Parallelforeach 将其加载到 ConcurrentDictionary

4

2 回答 2

2

计数超过 1K 条记录。

1K多多少?因为 1K 记录会在眨眼之间添加,不需要任何并行化。

此外,如果您通过网络获取数据,则该成本将大大超过添加到字典的成本。因此,除非您可以并行获取数据,否则使代码更复杂以将数据并行添加到字典是没有意义的。

于 2012-11-28T07:38:37.160 回答
1

这是一个老问题,但这可能对某人有所帮助:

如果您试图通过 ConcurrentDictionary 分块并进行一些处理:

using System.Collections.Generic;
using System.Threading.Tasks;
using System.Collections.Concurrent;

namespace ConcurrenyTests
{
    public class ConcurrentExample
    {
        ConcurrentExample()
        {
            ConcurrentDictionary<string, string> ConcurrentPairs = new ConcurrentDictionary<string, string>();

            Parallel.ForEach(ConcurrentPairs, (KeyValuePair<string, string> pair) =>
            {
                // Do Stuff with
                string key = pair.Key;
                string value = pair.Value;
            });
        }
    }
}

我认为您不能使用 Parallel.ForEach 来插入新字典,除非您已经有一个与您正在迭代的长度相同的对象。即包含您想要下载并插入到字典中的文本文档的 URL 列表。如果是这种情况,那么您可以使用以下内容:

using System.Threading.Tasks;
using System.Collections.Concurrent;

namespace ConcurrenyTests
{
    public class ConcurrentExample
    {
        ConcurrentExample()
        {
            ConcurrentDictionary<string, string> ConcurrentPairs = new ConcurrentDictionary<string, string>();
            ConcurrentBag<string> WebAddresses = new ConcurrentBag<string>();

            Parallel.ForEach(WebAddresses, new ParallelOptions { MaxDegreeOfParallelism = 4 }, (string webAddress) =>
            {
                // Fetch from webaddress
                string webText;
                // Try Add
                ConcurrentPairs.TryAdd(webAddress, webText);

                // GetOrUpdate
                ConcurrentPairs.AddOrUpdate(webAddress, webText, (string key, string oldValue) => webText);

            });
        }
    }
}

如果从网络服务器访问,您可能需要增加或减少 MaxDefreeOfParallelism,这样您的带宽就不会被阻塞。

Parallel.ForEach:https ://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.parallel.foreach?view=netcore-2.2

ParallelOptions:https ://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.paralleloptions?view=netcore-2.2

于 2019-09-27T00:20:06.800 回答