I have a thread #1 which is looping continuously with foreach through a ConcurrentBag list and modifying the items, but at some time another thread #2 needs to modify an item from the list. Is it safe if I take out all the objects from thread #2 (while the other one is looping with foreach) and modify the object then add all items back in thread #2 ? if it's not then is there a workaround ?
ConcurrentBag<MyObject> list;
thread 1
while (1) // continuous loop
{
foreach(MyObject obj in list)
{
obj.RunMethod();
Thread.Sleep(500);
}
Thread.Sleep(1000);
}
thread 2
(at some point a callback is called on thread #2 and need to modify an object)
List<MyObject> temp;
while (list.TryTake(out obj)
{
MyObject obj2=obj.Clone(); // make a copy of the object
if (obj2.Id==4) obj2.variable=10;
temp.Add(obj2);
}
// Add objects back to concurrentbag
foreach(MyObject obj in temp) list.Add(obj);