I have below code which will call couple of services and finally add the items to collection. But the problem is it’s not updating my list though I am using thread safe collection ConcurrentBag class. I am using Parellel.ForEach for fast performance for processing each request id. My code is compiling with no error, and I can see the values list while debugging but at the end of request getting null in response. Also sometimes, the code is getting executed twice when I do debugging. I am not sure is it because of Parellel.ForEach loop.
public async Task<ModifiedCollection> GetUpdates(Request request)
{
ModifiedCollection modifiedCollection = new ModifiedCollection();
List<string> Ids = request.Ids.Distinct().ToList();
if (Ids.Any())
{
Parallel.ForEach(Ids, async id =>
{
var globalId = "";
var result = await _provider.GetList(id, request.IsActive);
var baseValue = result.FirstOrDefault();
if (baseValue?.CustId.FirstOrDefault() == Constants.ABC)
{
var predicate = _provider.GetPredicate(
type: baseValue.type,
id: null);
var matter = await _provider.GetItem(request.IsActive, predicate);
if (matter != null && matter.CustId.Contains(request.ToRequest.CustId.FirstOrDefault()))
{
result = await _provider.GetList(matter.MapId, request.IsActive);
globalId = id;
}
}
result = BackDraw(result, request.FromRequest.CustId.FirstOrDefault());
Parallel.ForEach(result, async item =>
{
var IsValid = true;
if (!String.IsNullOrEmpty(request.ToRequest.EligDate))
IsValid = CheckEligibility(item, Convert.ToDateTime(request.ToRequest.EligDate));
if (IsValid)
{
var resultMatter = await _provider.GetStructure(item);
var uItem = await GetUItem(resultMatter);
if (uItem != null)
{
if (!uItem.rNotes.IsNullOrEmpty() && !uItem.property.IsNullOrEmpty())
{
modifiedCollection.ModifiedItem.Add(new ModifiedItem
{
Id = item.ObjectId,
Version = int.Parse(item.Version),
});
}
}
}
});
});
}
return modifiedCollection;
}
Class defination is as below
public class ModifiedCollection
{
public ConcurrentBag<ModifiedItem> ModifiedItemBag { get; set; }
public Updates()
{
UpdatesCollectionBag = new ConcurrentBag<ModifiedItem>();
}
}
If I replace the Parellel.ForEach with just foreach its working but the response time its taking is 8+ secs. How can I make this code work and fast as well. I have tried to add lock as well at the time of adding item to collection but still list if not getting updated and getting null response. I need to make improvements in performance of this code. Any help would be appreciated. TIA