I have both the regular for each loop and its equivalent paralleled version. The loop simply iterates through a collection, looking for the rate key in a local db
instance and then updating the topic code.
using (var db = new SomeEntities())
{
foreach (var measure in measures)
{
var keytofind= measure.RateKey.ToString(CultureInfo.InvariantCulture);
var firstOrDefault = db.RatesMappings.FirstOrDefault(r => r.RateKey == keytofind);
if (firstOrDefault != null)
measure.TopicCode = firstOrDefault.TopicCode;
}
Parallel.ForEach(measures, measure=>
{
var keytofind= rawDataMeasure.RateKey.ToString(CultureInfo.InvariantCulture);
lock(measure)
{
var firstOrDefault = db.RatesMappings.FirstOrDefault(r => r.RateKey == keytofind);
if (firstOrDefault != null)
measure.TopicCode = firstOrDefault.TopicCode;
}
});
}
Is the paralleled code correct and has the lock been placed correctly?