问题描述
例如,以下代码线程安全:
For example is the following code thread safe:
ConcurrentQueue<Guid> _queue = new ConcurrentQueue<Guid>();
while(true)
{
for(int y = 0; y < 3; y++)
{
if(y % 3 == 0)
{
System.Threading.Tasks.Task.Run(() => _queue.Enqueue(Guid.NewGuid()));
}
else if (y % 3 == 1)
{
Guid x;
System.Threading.Tasks.Task.Run(() => _queue.TryDequeue(out x));
}
else if(y % 3 == 2)
{
System.Threading.Tasks.Task.Run(() =>
{
if (_queue.Any(t => t == testGuid))
{
// Do something
}
});
}
}
显然标题不够清晰,因此更新了代码示例以包含实际的多线程行为,是的,上面的代码只是多线程行为的 sample .
Apparently the title wasn't clear enough so updated the code sample to include actual multi threaded behaviour, yes the code above is just a sample of multi-threaded behaviour.
推荐答案
LINQ操作是只读的,因此它们在 all 集合上是线程安全的.当然,如果您添加修改Where
或Select
方法内部集合的代码,它们将不再是线程安全的.
LINQ operations are read-only so they are thread safe on all collections. Of course, if you add code that modifies a collection inside the Where
or Select
method, they cease to be thread-safe.
线程安全的集合确保修改是线程安全的,这在执行LINQ查询时并不是真正的问题.
Thread-safe collections ensure that modifications are thread-safe, which isn't really a concern when executing a LINQ query.
在遍历期间修改集合是不安全的.普通集合在修改迭代器时会使迭代器无效,而线程安全集合不会使迭代器无效.在某些情况下(例如在ConcurrentQueue中),这是通过在迭代过程中呈现数据快照来实现的.
What isn't safe is modifying a collection during traversal. Normal collections invalidate iterators when they are modified, while the thread-safe collections do not. In some cases, (eg in ConcurrentQueue) this is achieved by presenting a snapshot of the data during iteration.
这篇关于并发集合上的linq操作线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!