问题描述
有没有办法同时添加多个项目到ConcurrentBag,而不是一次一个?我在ConcurrentBag上没有看到AddRange()方法,但是有一个Concat()。但是,这不适合我:
Is there a way to add multiple items to ConcurrentBag all at once, instead of one at a time? I don't see an AddRange() method on ConcurrentBag, but there is a Concat(). However, that's not working for me:
ConcurrentBag<T> objectList = new ConcurrentBag<T>();
timeChunks.ForEach(timeChunk =>
{
List<T> newList = Foo.SomeMethod<T>(x => x.SomeReadTime > timeChunk.StartTime);
objectList.Concat<T>(newList);
});
这段代码以前在Parallel.ForEach我可以解决它。变量newList确实具有对象,但是在objectList.Concat<>行之后,objectList总是具有0个对象。 Concat<>不是这样工作吗?
This code used to be in a Parallel.ForEach(), but I changed it to the above so I could troubleshoot it. The variable newList indeed has objects, but after the objectList.Concat<> line, objectList always has 0 objects in it. Does Concat<> not work that way? Do I need to add items to ConcurrentBag one at a time, with the Add() method?
推荐答案
是:)
Concat
可能是 Enumerable
扩展之一。它不会添加任何东西到 ConcurrentBag
,它只是返回一些时髦的对象包含原始的包和你尝试添加到那里。
Concat
is perhaps one of the Enumerable
extensions. It doesn't add anything to the ConcurrentBag
, it just returns some funky object containing the original bag and whatever you tried to add there.
注意, Concat
的结果不是 ConcurrentBag
,因此您不想用它。它是一般LINQ框架的一部分,使得可能组合不可变序列。当然,这个框架并不试图将操作数的并发属性扩展到结果,因此产生的对象将不太适合多线程访问。
Beware that the result of Concat
is not a ConcurrentBag
anymore, so you would not want to use it. It's a part of general LINQ framework, making possible to combine immutable sequences. This framework, of course, doesn't try to extend the concurrent properties of the operands to the result, so the resulting object will not be so well suited for multithreaded access.
(基本上, Concat
适用于 ConcurrentBag
,因为它暴露 IEnumerable< T& c $ c> interface。)
(Basically, Concat
applies to ConcurrentBag
because it exposes IEnumerable<T>
interface.)
这篇关于ConcurrentBag - 添加多个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!