I have gone through similar looking questions, where answers are suggesting to use lock
and not to modify List inside of foreach
loop on the same collection, I have already taken care of these two.
I have globally available List<Object>
and there are two different threads which are reading and writing in the list respectively.
To avoid race condition, I have used Lock
at both (reading[using linq] and writing).
and also I'm creating local copy, modify it and restore that copy to main copy (to reduce time of lock)
I guess while creating a local copy, it is having reference of main copy and thus main copy is being updated out side of lock too. Correct me here!
Including similar code for reference,
private void UpdateList(List<Object> newList)
{
List<Object> localCopyOfList;
lock(m_lockObj) //again a global object for locking
{
//I suspect it is reference type's problem here
localCopyOfList = m_globalCopyOfList;
}
foreach(Object obj in newList)
{
localCopyOfList.Add(obj);
}
lock(m_lockObj)
{
m_globalCopyOfList = localCopyOfList;
}
}
and for reading, I have method like,
private int GetTotalCount()
{
List<Object> localCopyOfList;
lock(m_lockObj) //again a global object for locking
{
localCopyOfList = m_globalCopyOfList;
}
//On following line I'm getting this exception
//Exceptions System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
return localCopyOfList.where(x => x.status == true).Count;
}