using ConcurrentStack
I need to use the stack data structure to save strings. But this stack will be accessed开发者_Python百科 from multiple threads. So my question is, how do I use the ConcurrentStack to add data from multiple threads?
Congratulations, you have chosen the correct container for multihreaded usage. The entire class is thread-safe, and recommended for your scenario, so just party on using Push
or PushRange
as appropriate.
The ranges example code here uses parallelization to demonstrate multithreaded operation.
You have received some pretty good answers so far. Let me provide some useful information regarding its design to help you better understand how it can be used. Notice that there is no Pop
method. That is because the designers wanted to prevent you from doing the following unsafe sequence of operations. It is unsafe because the sequence of calls to the Count
property and hypothetical Pop
method are not atomic despite the collection being billed as thread-safe.
while (stack.Count > 0)
{
stack.Pop();
}
To reconcile this common use case the designers used the TryPop
method instead. This essentially allows you to rewrite the above like the following. This time the code is safe.
object item;
while (stack.TryPop(out item))
{
// Do something with the item here.
}
A corollary to my first example exists with the Push
method as well. The following code (which is legal this time) is also unsafe.
if (stack.Count < MAX_ITEMS)
{
stack.Push(...);
}
The later example is not as common a use case as the former and that is probably why the designers did not add the CAS-like equivalent operation TryPush
. Perhaps in a future release that will be made available to us.
You create your ConcurrentStack<string>
, and make sure all of the threads have a reference to it.
The threads would then just call Push to add strings:
theStack.Push("foo");
Adding values to a ConcurrentStack
from multiple threads is fairly straight forward. Just make a reference to the stack available and call Push
from whichever thread needs to add data. No special locking is needed here as the collection is designed to be used from multiple threads in this manner.
One on thread use:
_stack.Push(obj);
On another thread use:
MyObj obj;
if (_stack.TryPop(out obj))
UseObj(obj);
I recommend reading this MSDN blog post.
精彩评论