如下所示,ConcurrentQueue做到了代码的简化,在并发模型中充当同步对象

private ConcurrentQueue<string> inQueue = new ConcurrentQueue<string>();

private object lockObject = new object();
private Queue<string> queue = new Queue<string>();

MSDN例子(还是并行库强大):

        static void Main(string[] args)
{
// Construct a ConcurrentQueue.
ConcurrentQueue<int> cq = new ConcurrentQueue<int>(); // Populate the queue.
for (int i = ; i < ; i++) cq.Enqueue(i); // Peek at the first element.
int result;
if (!cq.TryPeek(out result))
{
Console.WriteLine("CQ: TryPeek failed when it should have succeeded");
}
else if (result != )
{
Console.WriteLine("CQ: Expected TryPeek result of 0, got {0}", result);
} int outerSum = ;
// An action to consume the ConcurrentQueue.
Action action = () =>
{
int localSum = ;
int localValue;
while (cq.TryDequeue(out localValue)) localSum += localValue;
Interlocked.Add(ref outerSum, localSum);
}; // Start 4 concurrent consuming actions.
Parallel.Invoke(action, action, action, action); Console.WriteLine("outerSum = {0}, should be 49995000", outerSum);
}
05-06 01:56