Concurrent Queue

The ConcurrentQueue class implements a first in, first out (FIFO) queue, which means that when you take items from the queue, you get them in the same order in which they were added. To place an item into a ConcurrentQueue, you call the Enqueue() method. To take the first item in the queue, you call TryDequeue() and to get the first item in the queue without taking it, you call TryPeek().

TryDequeue() and TryPeek() take a parameter of the collection type, modified by the out keyword and return a bool result. If the result is true, the parameter will contain the data item. If it is false, no data item could be obtained. Listing 3-18 shows how to use the ConcurrentQueue class to resolve the data race demonstrated in Listing 3-17.

Listing3-18. Using the ConcurrentQueue Class using System;

using System.Collections.Concurrent; using System.Threading; using System.Threading.Tasks;

namespace Listing_18 {

class Listing_18 {

static void Main(string[] args) {

// create a shared collection

0 0

Post a comment