Queues

A 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.

Table 9-4. Queue methods and properties

Method or property

Purpose

Synchronized( )

Public static method that returns a Queue wrapper that is thread-safe.

Count

Public property that gets the number of elements in the Queue.

IsSynchronized

Public property to get a value indicating if the Queue is synchronized.

SyncRoot

Public property that returns an object that can be used to synchronize access to the Queue.

Clear( )

Removes all objects from the Queue.

Clone( )

Creates a shallow copy.

Contains( )

Determines if an element is in the Queue.

CopyTo( )

Copies the Queue elements to an existing one-dimensional array.

Dequeue( )

Removes and returns the object at the beginning of the Queue.

Enqueue( )

Adds an object to the end of the Queue.

GetEnumerator( )

Returns an enumerator ...

Get Programming C#, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.