本体内で集中的な操作を実行する Parallel.ForEach ループがあります。
この操作では、Hashtable を使用して値を格納し、他の連続するループ項目に再利用できます。集中的な操作が完了した後に Hashtable に追加すると、集中的な操作を再度実行する代わりに、次のループ項目が Hashtable を検索してオブジェクトを再利用できます。
ただし、私は Parallel.ForEach を使用しているため、Hashtable.Add と ContainsKey(key) 呼び出しが並行して実行されている可能性があるため、非同期になるという安全でない問題があります。ロックを導入すると、パフォーマンスの問題が発生する可能性があります。
サンプルコードは次のとおりです。
Hashtable myTable = new Hashtable;
Parallel.ForEach(items, (item, loopState) =>
{
// If exists in myTable use it, else add to hashtable
if(myTable.ContainsKey(item.Key))
{
myObj = myTable[item.Key];
}
else
{
myObj = SomeIntensiveOperation();
myTable.Add(item.Key, myObj); // Issue is here : breaks with exc during runtime
}
// Do something with myObj
// some code here
}
このシナリオを処理できる API、TPL ライブラリ内のプロパティ設定が必要です。ある?