Consider the following function, which iterates over the generic List<T>
: Items, and changes a matching item if found:
void UpdateList(ref List<clsMyClass> Items, int idToFind) {
foreach(var Item in Items) {
if (Item.ID == idToFind)
{
// modify the item
Item.SomeIntCounter++;
return;
}
}
}
Now, if I wanted to do the same thing, but this time using a thread-safe ConcurrentBag<T>
, is this an acceptable method?...
void UpdateList(ref ConcurrentBag<clsMyClass> Items, int idToFind) {
clsMyClass Item;
bool found = false;
ConcurrentBag<clsMyClass> tempItems = new ConcurrentBag<clsMyClass>();
while(Items.Count > 0) {
if (Items.TryTake(out Item))
{
if (Item.ID == idToFind)
{
//modify the item
Item.SomeIntCounter++;
found = true;
}
tempItems.Add(Item);
if (found) break;
}
}
foreach(var tempItem in tempItems) Items.Add(tempItem);
}
The idea here is that every item is removed from the ConcurrentBag and added to a temporary one until the matching item is found and changed, after this all the removed items are re-added to the ConcurrentBag.
Is this a sensible way to modify the collection in a thread safe way?