Queues work much as they soundthey are first-in, first-out (FIFO) collections, like when you stand in line for tickets. These collections are good when you have a group of objects you want to process as they come in, such as when you receive client requests to connect to a Web service. Queues are supported with the Queue class. You can see the significant public properties of Queue objects in Table 6.7, and their significant public methods in Table 6.8. You use the Enqueue method to add items to the end of a queue and Dequeue to remove the first item from the front of the queue. Table 6.7. Significant Public Properties of Queue Objects
Table 6.8. Significant Public Methods of Queue Objects
You can see an example in ch06_07.cs, Listing 6.7, where we're adding items to a queue: Queue queue = new Queue(); queue.Enqueue(0); queue.Enqueue(1); queue.Enqueue(2); queue.Enqueue(3); queue.Enqueue(4); We then de-queue one or two items to confirm that they come off the front of the queue: System.Console.WriteLine("Dequeued {0}", queue.Dequeue()); You can see the code in Listing 6.7. Note that as with the other C# collections, you can iterate over the members of a queue using foreach . This is done in ch06_07.cs to display everything that's in the queue. Listing 6.7 Creating a Queue (ch06_07.cs)using System.Collections; public class ch06_07 { static void Main() { Queue queue = new Queue(); System.Console.WriteLine("Queuing 0 1 2 3 4"); queue.Enqueue(0); queue.Enqueue(1); queue.Enqueue(2); queue.Enqueue(3); queue.Enqueue(4); System.Console.Write("The queue: "); foreach(object obj in queue) { System.Console.Write("{0} ", obj); } System.Console.WriteLine(); System.Console.WriteLine("Dequeued {0}", queue.Dequeue()); System.Console.Write("The queue: "); foreach(object obj in queue) { System.Console.Write("{0} ", obj); } System.Console.WriteLine(); System.Console.WriteLine("Dequeued {0}", queue.Dequeue()); System.Console.Write("The queue: "); foreach(object obj in queue) { System.Console.Write("{0} ", obj); } System.Console.WriteLine(); } } Here's what you see when you run ch06_07: C:\>ch06_07 Queuing 0 1 2 3 4 The queue: 0 1 2 3 4 Dequeued 0 The queue: 1 2 3 4 Dequeued 1 The queue: 2 3 4 Here, we've queued 0, 1, 2, 3, and 4; when we de-queue a value, 0 comes off the front of the stack. When we de-queue another value, 1 comes off. Note that you can also check the next value about to come off the queue with the Peek method, which returns that value without actually removing it from the queue. |