Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

c# - Does BlockingCollection<T> guarantee removal order?

I have a bounded blocking queue in an application that was written several years ago. Let's just say that the implementation is less than stellar, but it's worked. However, it has some performance problems. It looks like the .NET 4.0 BlockingCollection<T> is the right replacement, but I need to make sure that it is actually a queue. That is, is it guaranteed to be strictly FIFO if used in a single-producer, single-consumer fashion?

The documentation doesn't specifically say. The BlockingCollection topic does say (in the Remarks):

BlockingCollection<T> is similar to a traditional blocking queue data structure, except that the underlying data storage mechanism is abstracted away as an IProducerConsumerCollection<T>.

But nothing specifically says that things will be removed in the same order they're added.

Anybody know for sure?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, BlockingCollection<T> is really designed for parallel work, where you have multiple simulataneous "producers" and one consumer (using GetConsumingEnumerable()).

In this situation, you have no way to guarantee insertion order, so the ordering constraints aren't specified.

That being said, BlockingCollection<T> works upon any IProducerConsumerCollection<T> (specified in the constructor). If you don't provide one in the constructor, internally, it will use a ConcurrentQueue<T>. This causes it to be FIFO, since it will actually be (internally) a queue. So yes, by default, it will be "guaranteed to be strictly FIFO if used in a single-producer, single-consumer fashion", at least in the current implementation. If you want to force this for future proofing (since the queue is an implementation detail), just construct it as:

var blockingCollection = new BlockingCollection<MyClass>(new ConcurrentQueue<MyClass>());

That will guarantee that it uses a queue now, and in the future (since the queue is an implementation detail).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...