I am trying to query a mongo-db parallely using Parallel.Foreach()
but I am not getting any results. But when I try to run the same thing in regular foreach loop I am able to perform the expected tasks.
var exceptions = new ConcurrentQueue<Exception>();
var secondaryObjectsDictionaryCollection = new Dictionary<string, List<JObject>>();
// This works
foreach(var info in infos)
{
try
{
name = await commonValidator.ValidateAsync(name);
await commonValidator.ValidateIdAsync(name, id);
var list = await helper.ListRelatedObjectsAsync(name, id, info, false);
secondaryObjectsDictionaryCollection.Add(info.PrimaryId, secondaryObjectsList.ToList());
}
catch (Exception ex)
{
exceptions.Enqueue(ex);
}
}
//This does not
Parallel.ForEach(infos, async info =>
{
try
{
name = await commonValidator.ValidateAsync(name);
await commonValidator.ValidateIdAsync(name, id);
var list = await helper.ListRelatedObjectsAsync(name, id, info, false);
secondaryObjectsDictionaryCollection.Add(info.PrimaryId, secondaryObjectsList.ToList());
}
catch (Exception ex)
{
exceptions.Enqueue(ex);
}
});
I want to perform this task in parallel only since different mongodb collections are involved and also to reduce the response time.
I am not able to figure out what's getting wrong in my parallel loop. Any other approach to perform these tasks in parallel will also work.