Using ConcurrentStack

I need to use a stack data structure to store strings. But this stack will be available from multiple threads. So my question is: how can I use ConcurrentStack to add data from multiple threads?

+3
source share
5 answers

Congratulations, you have chosen the right container for multi-threaded use. The whole class is thread safe and recommended for your scenario, so just use Pushor if necessary PushRange.

The range code example here uses parallelization to demonstrate multi-threaded operation.

+8

. , , . , Pop. , . , Count Pop , , ​​ .

while (stack.Count > 0)
{
  stack.Pop();
}

, TryPop. , , , . .

object item;
while (stack.TryPop(out item))
{
  // Do something with the item here.
}

Push. ( ) .

if (stack.Count < MAX_ITEMS)
{
  stack.Push(...);
}

, , , CAS- TryPush. , , .

+8

ConcurrentStack<string> , .

Push, :

theStack.Push("foo");
+1

Adding values ​​to ConcurrentStackfrom multiple threads is pretty straight forward. Just make a link to an available stack and call Pushfrom any thread that needs to add data. There is no special lock here, as the collection is intended to be used from multiple threads in this way.

+1
source

One when using stream:

_stack.Push(obj);

In another thread, use:

MyObj obj;    
if (_stack.TryPop(out obj))
    UseObj(obj);

I recommend reading this MSDN blog post .

+1
source

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


All Articles