Foreach 循环和带锁定的变量 [英] 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?
推荐答案
你可以为你的 changedItems 使用 ConcurrentCollection.像 ConcurrentQueue 这样的东西?那么你根本不需要锁定.
Could you use a ConcurrentCollection for your changedItems. Something like ConcurrentQueue? Then you wouldn't need to lock at all.
更新:
关于 ConcurrentQueue,Enqueue 不会阻塞线程以保证操作线程安全.它通过 SpinWait 保持在用户模式...
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...
public void Enqueue(T item)
{
SpinWait wait = new SpinWait();
while (!this.m_tail.TryAppend(item, ref this.m_tail))
{
wait.SpinOnce();
}
}
这篇关于Foreach 循环和带锁定的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!