Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach loop and variables with locking

Basically what I want to do is this psuedo code

List<DatabaseRecord> records;

List<ChangedItem> changedItems;

Parallel.ForEach<DatabaseRecord>(records, (item, loopState) =>
{
    if (item.HasChanged)
    {
        lock (changedItems)
        {
            changedItems.Add(new ChangedItem(item));
        }
    }
});

But what I'm worried about is locking on the changedItems. While it works, I have heard that it has to serialize the locked object over and over. Is there a better way of doing this?

like image 310
Rick Rat Avatar asked Feb 22 '26 09:02

Rick Rat


1 Answers

Why don't you use PLinq instead? No locking needed:

changedItems = records.AsParallel()
                      .Where(x => x.HasChanged)
                      .Select(x => new ChangedItem(x))
                      .ToList();

Since you are projecting into a new list of ChangedItem and do not have any side effects this would be the way to go in my opinion.

like image 158
BrokenGlass Avatar answered Feb 23 '26 22:02

BrokenGlass



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!