I have a Parallel.ForEach loop performing an intensive operation inside the body.
An operation can use a hashtable to store values ββand can be reused for other consecutive elements of the loop. I add to the Hashtable after the intensive operation is completed, the next element of the loop can search in the Hashtable and reuse the object, instead of performing the intensive operation again.
However, since I use Parallel.ForEach, an unsafe problem arises, as a result of which the calls to Hashtable.Add and ContainsKey (key) go out of sync, as they can be executed in parallel. The use of interlocks can cause perforation problems.
Here is a sample code:
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 }
Inside the TPL library, there must be some API, a property parameter, that this script could handle. There is?
Vin
source share