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?
Could you use a ConcurrentCollection for your changedItems. Something like ConcurrentQueue? Then you wouldn’t need to lock at all.
Update:
With regard to the ConcurrentQueue, the Enqueue won’t block the thread in keeping the operation thread safe. It stays in user mode with a SpinWait…