Is ConcurrentBag (T) optimized for single-threaded scripts? If so, why at the same time?

The MSDN documentation in the ConcurrentBag<T> class from the .NET 4.0 Parallel Collection Library says the following:

ConcurrentBag is a thread-safe implementation package, optimized for scenarios in which the same stream will be both production and data consumption is stored in the bag . [emphasis mine]

Am I missing something, or does it mean that the ConcurrentBag<T> class is optimized for single-threaded scripts?

If I didn’t miss something ... why is this so? It seems rather strange to create a collection designed for concurrency, but optimized for a single thread.

+4
source share
3 answers

Optimization means that if you have several threads producing and consuming, there are optimizations such that they are faster if they can return an item placed in the bag by the same thread.

If this optimization is not applied, this is if the thread requests a bag for the item and there are more items left in the bag that were placed there by this thread. In this case, he can still remove the item from the bag (put there with another thread), but it is less optimal.


Or, to put it another way: This is in parallel, because several flows and consuming it simultaneously, without external blocking, can enter it. The specified optimization does not make this incorrect.

+1
source

What the documentation is trying to say is that it prefers the same stream that produces and consumes data.

This has a quick way, when the same thread produces and consumes data, the data remains in this thread (I think [ThreadStatic] ). However, when there is no data to consume in one thread, it scans the other threads and receives data from there.

Take a look, for example. at http://www.codethinked.com/post/2010/01/27/NET-40-and-System_Collections_Concurrent_ConcurrentBag.aspx for a more detailed explanation of this.

+1
source

Three scenarios where you can use ConcurrentBag and how this optimization affects them:

1) Separate flows of producers and consumers. No effect.

2) Topics that are both consumers and producers that store and retrieve data from ConcurrentBag . Optimization will improve performance for add / receive operations on a single thread.

3) Single threaded scripts that can use a regular collection. Optimization means that when using ConcurrentBag there is little overhead, so you can use it without huge success.

+1
source

Source: https://habr.com/ru/post/1337729/


All Articles