[ Team LiB ] |
9.6 QueuesA queue represents a first-in, first-out (FIFO) collection. The classic analogy is to a line (or queue if you are British) at a ticket window. The first person in line ought to be the first person to come off the line to buy a ticket. A queue is a good collection to use when you are managing a limited resource. For example, you might want to send messages to a resource that can only handle one message at a time. You would then create a message queue so that you can say to your clients: "Your message is important to us. Messages are handled in the order in which they are received." The Queue class has a number of member methods and properties, as shown in Table 9-4.
Add elements to your queue with the Enqueue command and take them off the queue with Dequeue or by using an enumerator. Example 9-15 illustrates. Example 9-15. Working with a queuenamespace Programming_CSharp { using System; using System.Collections; public class Tester { static void Main( ) { Queue intQueuee = new Queue( ); // populate the array for (int i = 0;i<5;i++) { intQueuee.Enqueue(i*5); } // Display the Queue. Console.Write( "intQueuee values:\t" ); PrintValues( intQueuee ); // Remove an element from the queue. Console.WriteLine( "\n(Dequeue)\t{0}", intQueuee.Dequeue( ) ); // Display the Queue. Console.Write( "intQueuee values:\t" ); PrintValues( intQueuee ); // Remove another element from the queue. Console.WriteLine( "\n(Dequeue)\t{0}", intQueuee.Dequeue( ) ); // Display the Queue. Console.Write( "intQueuee values:\t" ); PrintValues( intQueuee ); // View the first element in the // Queue but do not remove. Console.WriteLine( "\n(Peek) \t{0}", intQueuee.Peek( ) ); // Display the Queue. Console.Write( "intQueuee values:\t" ); PrintValues( intQueuee ); } public static void PrintValues( IEnumerable myCollection ) { IEnumerator myEnumerator = myCollection.GetEnumerator( ); while ( myEnumerator.MoveNext( ) ) Console.Write( "{0} ",myEnumerator.Current ); Console.WriteLine( ); } } } Output: intQueuee values: 0 5 10 15 20 (Dequeue) 0 intQueuee values: 5 10 15 20 (Dequeue) 5 intQueuee values: 10 15 20 (Peek) 10 intQueuee values: 10 15 20 In this example the ArrayList is replaced by a Queue. I've dispensed with the Employee class to save room, but of course you can Enqueue user-defined objects as well. The output shows that queuing objects adds them to the Queue, and calls to Dequeue return the object and also remove them from the Queue. The Queue class also provides a Peek( ) method that allows you to see, but not remove, the first element. Because the Queue class is enumerable, you can pass it to the PrintValues method, which is provided as an IEnumerable interface. The conversion is implicit. In the PrintValues method you call GetEnumerator, which you will remember is the single method of all IEnumerable classes. This returns an IEnumerator, which you then use to enumerate all the objects in the collection. |
[ Team LiB ] |