これは静かな古い質問ですが、これは誰かを助けるかもしれません:
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);
});
}
}
}
Webサーバーからアクセスする場合は、帯域幅が詰まらないように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