清单< T>线程安全 [英] List<T> thread safety

查看:170
本文介绍了清单< T>线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是低于code

I am using the below code

var processed = new List<Guid>();
Parallel.ForEach(items, item => 
{
    processed.Add(SomeProcessingFunc(item));
});

是上面code线程安全的?有没有得到破坏处理列表的机会呢?或者我应该将之前使用锁?

Is the above code thread safe? Is there a chance of processed list getting corrupted? Or should i use a lock before adding?

var processed = new List<Guid>();
Parallel.ForEach(items, item => 
{
    lock(items.SyncRoot)
        processed.Add(SomeProcessingFunc(item));
});

感谢。

推荐答案

没有!它是不是安全可言,因为 processed.Add 不是。你可以做到以下几点:

No! It is not safe at all, because processed.Add is not. You can do following:

items.AsParallel().Select(item => SomeProcessingFunc(item)).ToList();

请即 Parallel.ForEach 大部分是创造的必须的对序列的每个元素的操作。你要做的就是地图:项目序列的每个值。这就是选择是为创建。 进行AsParallel 扩展它在线程中最有效的方式。

Keep in mind that Parallel.ForEach was created mostly for imperative operations for each element of sequence. What you do is map: project each value of sequence. That is what Select was created for. AsParallel scales it across threads in most efficient manner.

这code正常工作:

var processed = new List<Guid>();
Parallel.ForEach(items, item => 
{
    lock(items.SyncRoot)
        processed.Add(SomeProcessingFunc(item));
});

而使得多线程方面没有任何意义。 锁定 ING在每次迭代的力量完全顺序执行,一堆线程将等待单个线程。

but makes no sense in terms of multithreading. locking at each iteration forces totally sequential execution, bunch of threads will be waiting for single thread.

这篇关于清单&LT; T&GT;线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆