Don't use ConcurrentBag<T>
to replace a locked List<T>
unless you're certain of your thread's access patterns because it uses thread local storage under the covers.
MSDN talks about the preferred usage:
"ConcurrentBag<T>
is a thread-safe bag implementation, optimized for scenarios where the same thread will be both producing and consuming data stored in the bag."
It's also important to note that List<T>
is ordered and ConcurrentBag<T>
is unordered. If you don't care about order in your collection I would use a ConcurrentQueue<T>
.
Regarding performance, below is some code from ConcurrentBag<T>
. But the primary thing to consider is if you do a Take
and your thread local storage is empty it will steal from other threads which is expensive.
When it needs to steal, note that it is locking. Also note it can lock several times on one Take
since TrySteal
can fail and get called more than once from Steal
(not shown).
private bool TrySteal(ConcurrentBag<T>.ThreadLocalList list, out T result, bool take)
{
lock (list)
{
if (this.CanSteal(list))
{
list.Steal(out result, take);
return true;
}
result = default (T);
return false;
}
}
There is also possible spin waiting during CanSteal
.
private bool CanSteal(ConcurrentBag<T>.ThreadLocalList list)
{
if (list.Count <= 2 && list.m_currentOp != 0)
{
SpinWait spinWait = new SpinWait();
while (list.m_currentOp != 0)
spinWait.SpinOnce();
}
return list.Count > 0;
}
And finally, even adding can cause a lock to be taken.
private void AddInternal(ConcurrentBag<T>.ThreadLocalList list, T item)
{
bool lockTaken = false;
try
{
Interlocked.Exchange(ref list.m_currentOp, 1);
if (list.Count < 2 || this.m_needSync)
{
list.m_currentOp = 0;
Monitor.Enter((object) list, ref lockTaken);
}
list.Add(item, lockTaken);
}
finally
{
list.m_currentOp = 0;
if (lockTaken)
Monitor.Exit((object) list);
}
}
lock(List<T>)
will not even compile).ConcurrentStack
orConcurrentQueue
?