以线程安全的方式添加到Parallel.ForEach循环中的列表 [英] Adding to a list in a Parallel.ForEach loop in a threadsafe manner

查看:305
本文介绍了以线程安全的方式添加到Parallel.ForEach循环中的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在称为ListofObjects的obj对象列表上,我有一些类似的代码:

I have a bit of code that works like this on a list of obj objects called ListofObjects:

List<SomeObject> NewListofObjects<SomeObject>();

Parallel.ForEach(ListofObjects, obj =>

//Do some operations here on obj to get a newobj

NewListofObjects.Add(newobj);

);

现在我不在Parallel.ForEach循环中,我想对NewListofObjects进行操作.但是,尝试执行以下操作时会出现此错误:试图读取或写入受保护的内存.这通常表明其他内存已损坏".

Now I am out of the Parallel.ForEach loop, and I want to do an operation on NewListofObjects. However, I get this error when I try to: "Attempted to read or write protected memory. This is often an indication that other memory is corrupt".

这是因为我的NewListofObjects.Add(newobj)方法不是线程安全的吗?如果是这样,如何使它具有线程安全性?

Is this because my NewListofObjects.Add(newobj) method is not threadsafe? If so, how can I make it threadsafe?

推荐答案

这是因为我的NewListofObjects.Add(newobj)方法不是线程安全的吗?

Is this because my NewListofObjects.Add(newobj) method is not threadsafe?

正确.它不是线程安全的.

Correct. It is not threadsafe.

不保证任何实例成员都是线程安全的.

Any instance members are not guaranteed to be thread safe.

来自 MSDN ,指的是List<T>(滚动到标题为线程安全"的部分.)

That's from MSDN referring to List<T> (scroll to the section titled "Thread Safety").

如果是这样,如何使它具有线程安全性?

If so, how can I make it threadsafe?

使用并发集合,例如 ConcurrentBag<T> .请注意,您失去了跟踪项目插入顺序的能力.

Use a concurrent collection, like ConcurrentBag<T>. Note that you lose the ability to keep track of the order that items were inserted.

这篇关于以线程安全的方式添加到Parallel.ForEach循环中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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