System.Collections.Queue Class

Assembly: Mscorlib.dll
Namespace: System.Collections
Summary
Represents a first-in, first-out collection of objects.
C# Syntax:
[Serializable]
public class Queue : ICollection, IEnumerable, ICloneable
Thread Safety
Public static (non-instance) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

To guarantee the thread safety of the Queue, all operations must be done through the wrapper returned by the Queue.Synchronized method.

Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

Remarks
Queues are useful for storing messages in the order they were received for sequential processing. This class implements a queue as a circular array. Objects stored in a Queue are inserted at one end and removed from the other. If the number of elements added to the Queue reaches the current capacity, the capacity is automatically increased to accommodate more elements. The capacity can be decreased by calling Queue.TrimToSize.
Example
The following example shows how to create and add values to a Queue and how to print out its values.
 using System;
 using System.Collections;
 public class SamplesQueue  {
 
    public static void Main()  {
 
       // Creates and initializes a new Queue.
       Queue myQ = new Queue();
       myQ.Enqueue("Hello");
       myQ.Enqueue("World");
       myQ.Enqueue("!");
 
       // Displays the properties and values of the Queue.
       Console.WriteLine( "myQ" );
       Console.WriteLine( "\tCount:    {0}", myQ.Count );
       Console.Write( "\tValues:" );
       PrintValues( myQ );
    }
 
 
    public static void PrintValues( IEnumerable myCollection )  {
       System.Collections.IEnumerator myEnumerator = myCollection.GetEnumerator();
       while ( myEnumerator.MoveNext() )
          Console.Write( "\t{0}", myEnumerator.Current );
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 myQ
     Count:    3
     Values:    Hello    World    !
*/ 

    
See also:
System.Collections Namespace

System.Collections.Queue Member List:

Public Constructors
ctor #1 Overloaded:
.ctor()

Default constructor. This constructor is called by derived class constructors to initialize state in this type.
Initializes a new instance of the Queue class that is empty, has the default initial capacity and uses the default growth factor.
ctor #2 Overloaded:
.ctor(ICollection col)

Initializes a new instance of the Queue class that contains elements copied from the specified collection, has the same initial capacity as the number of elements copied and uses the default growth factor.
ctor #3 Overloaded:
.ctor(int capacity)

Initializes a new instance of the Queue class that is empty, has the specified initial capacity and uses the default growth factor.
ctor #4 Overloaded:
.ctor(int capacity, float growFactor)

Initializes a new instance of the Queue class that is empty, has the specified initial capacity and uses the specified growth factor.
Public Properties
Count Read-only

Gets the number of elements contained in the Queue.
IsSynchronized Read-only

Gets a value indicating whether access to the Queue is synchronized (thread-safe).
SyncRoot Read-only

Gets an object that can be used to synchronize access to the Queue.
Public Methods
Clear Removes all objects from the Queue.
Clone Creates a shallow copy of the Queue.
Contains Determines whether an element is in the Queue.
CopyTo Copies the Queue elements to an existing one-dimensional Array, starting at the specified array index.
Dequeue Removes and returns the object at the beginning of the Queue.
Enqueue Adds an object to the end of the Queue.
Equals
(inherited from System.Object)
See base class member description: System.Object.Equals

Derived from System.Object, the primary base class for all objects.
GetEnumerator Returns an enumerator that can iterate through the Queue.
GetHashCode
(inherited from System.Object)
See base class member description: System.Object.GetHashCode

Derived from System.Object, the primary base class for all objects.
GetType
(inherited from System.Object)
See base class member description: System.Object.GetType

Derived from System.Object, the primary base class for all objects.
Peek Returns the object at the beginning of the Queue without removing it.
Synchronized Returns a Queue wrapper that is synchronized (thread-safe).
ToArray Copies the Queue elements to a new array.
ToString
(inherited from System.Object)
See base class member description: System.Object.ToString

Derived from System.Object, the primary base class for all objects.
TrimToSize Sets the capacity to the actual number of elements in the Queue.
Protected Methods
Finalize
(inherited from System.Object)
See base class member description: System.Object.Finalize

Derived from System.Object, the primary base class for all objects.
MemberwiseClone
(inherited from System.Object)
See base class member description: System.Object.MemberwiseClone

Derived from System.Object, the primary base class for all objects.

Hierarchy:


System.Collections.Queue Member Details

Overloaded ctor #1
Summary
Initializes a new instance of the Queue class that is empty, has the default initial capacity and uses the default growth factor.

Default constructor. This constructor is called by derived class constructors to initialize state in this type.
C# Syntax:
public Queue();
Remarks
The initial capacity is the starting capacity of the new Queue. The growth factor is the number by which the current capacity is multiplied when a greater capacity is required. The default initial capacity is 32 and the default growth factor is 2.0.

If the number of elements added to the Queue reaches the current capacity, the capacity is automatically increased. The new capacity is determined by multiplying the current capacity by the growth factor.

Return to top


Overloaded ctor #2
Summary
Initializes a new instance of the Queue class that contains elements copied from the specified collection, has the same initial capacity as the number of elements copied and uses the default growth factor.
C# Syntax:
public Queue(
   ICollection col
);
Parameters:

col

The ICollection to copy elements from.

Exceptions
Exception Type Condition
ArgumentNullException col is null.
Remarks
The initial capacity is the starting capacity of the new Queue. The growth factor is the number by which the current capacity is multiplied when a greater capacity is required. The default initial capacity is 32 and the default growth factor is 2.0.

The elements are copied onto the Queue in the same order they are read by the IEnumerator of the ICollection.

If the number of elements added to the Queue reaches the current capacity, the capacity is automatically increased. The new capacity is determined by multiplying the current capacity by the growth factor.

See also:
ICollection

Return to top


Overloaded ctor #3
Summary
Initializes a new instance of the Queue class that is empty, has the specified initial capacity and uses the default growth factor.
C# Syntax:
public Queue(
   int capacity
);
Parameters:

capacity

The initial number of elements that the Queue can contain.

Exceptions
Exception Type Condition
ArgumentOutOfRangeException capacity is less than zero.
Remarks
The initial capacity is the starting capacity of the new Queue. The growth factor is the number by which the current capacity is multiplied when a greater capacity is required. The default initial capacity is 32 and the default growth factor is 2.0.

If the number of elements added to the Queue reaches the current capacity, the capacity is automatically increased. The new capacity is determined by multiplying the current capacity by the growth factor.

If the size of the collection can be estimated, specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Queue.

Return to top


Overloaded ctor #4
Summary
Initializes a new instance of the Queue class that is empty, has the specified initial capacity and uses the specified growth factor.
C# Syntax:
public Queue(
   int capacity,
   float growFactor
);
Parameters:

capacity

The initial number of elements that the Queue can contain.

growFactor

The factor by which the capacity of the Queue is expanded.

Exceptions
Exception Type Condition
ArgumentOutOfRangeException capacity is less than zero.

-or-

growFactor is less than 1.0 or greater than 10.0.

Remarks
The initial capacity is the starting capacity of the new Queue. The growth factor is the number by which the current capacity is multiplied when a greater capacity is required. The default initial capacity is 32 and the default growth factor is 2.0.

If the number of elements added to the Queue reaches the current capacity, the capacity is automatically increased. The new capacity is determined by multiplying the current capacity by the growth factor.

If the size of the collection can be estimated, specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Queue.

Return to top


Property: Count (read-only)
Summary
Gets the number of elements contained in the Queue.
C# Syntax:
public virtual int Count {get;}
Implements:
ICollection.Count
Remarks
Queue.Count is the number of elements that are actually in the Queue. The capacity of a Queue is the number of elements that the Queue is capable of storing.

Queue.Count is always less than or equal to the capacity of the Queue. If Queue.Count exceeds the capacity of the Queue while adding elements, the capacity is increased by automatically reallocating the internal array before copying the old elements and adding the new element. The new capacity is determined by multiplying the current capacity by the growth factor, which is determined when the Queue is constructed.

Return to top


Property: IsSynchronized (read-only)
Summary
Gets a value indicating whether access to the Queue is synchronized (thread-safe).
C# Syntax:
public virtual bool IsSynchronized {get;}
Implements:
ICollection.IsSynchronized
Remarks
To guarantee the thread safety of the Queue, all operations must be done through the wrapper returned by the Queue.Synchronized method.

Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

The following code example shows how to lock the collection using the Queue.SyncRoot during the entire enumeration:

              Queue myCollection = new Queue();
               lock( myCollection.SyncRoot ) {
               foreach ( Object item in myCollection ) {
               // Insert your code here.
               }
              }
            
Example
The following example shows how to synchronize a Queue, determine if a Queue is synchronized and use a synchronized Queue.
 using System;
 using System.Collections;
 public class SamplesQueue  {
 
    public static void Main()  {
 
       // Creates and initializes a new Queue.
       Queue myQ = new Queue();
       myQ.Enqueue( "The" );
       myQ.Enqueue( "quick" );
       myQ.Enqueue( "brown" );
       myQ.Enqueue( "fox" );
 
       // Creates a synchronized wrapper around the Queue.
       Queue mySyncdQ = Queue.Synchronized( myQ );
 
       // Displays the sychronization status of both Queues.
       Console.WriteLine( "myQ is {0}.", myQ.IsSynchronized ? "synchronized" : "not synchronized" );
       Console.WriteLine( "mySyncdQ is {0}.", mySyncdQ.IsSynchronized ? "synchronized" : "not synchronized" );
    }
 }
 /* 
 This code produces the following output.
 
 myQ is not synchronized.
 mySyncdQ is synchronized.
 */ 

    
See also:
Queue.SyncRoot | Queue.Synchronized

Return to top


Property: SyncRoot (read-only)
Summary
Gets an object that can be used to synchronize access to the Queue.
C# Syntax:
public virtual object SyncRoot {get;}
Implements:
ICollection.SyncRoot
Remarks
To create a synchronized version of the Queue, use the Queue.Synchronized method. However, derived classes can provide their own synchronized version of the Queue using the Queue.SyncRoot property. The synchronizing code must perform operations on the Queue.SyncRoot of the Queue, not directly on the Queue. This ensures proper operation of collections that are derived from other objects. Specifically, it maintains proper synchronization with other threads that might be simultaneously modifying the Queue object.

Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

The following code example shows how to lock the collection using the Queue.SyncRoot during the entire enumeration:

              Queue myCollection = new Queue();
               lock( myCollection.SyncRoot ) {
               foreach ( Object item in myCollection ) {
               // Insert your code here.
               }
              }
            
See also:
Queue.IsSynchronized | Queue.Synchronized

Return to top


Method: Clear()
Summary
Removes all objects from the Queue.
C# Syntax:
public virtual void Clear();
Remarks
Queue.Count is set to zero. To reset the capacity of the Queue, call Queue.TrimToSize. Trimming an empty Queue sets the capacity of the Queue to the default capacity, not zero.
Example
The following example shows how to clear the values of the Queue.
 using System;
 using System.Collections;
 public class SamplesQueue  {
 
    public static void Main()  {
 
       // Creates and initializes a new Queue.
       Queue myQ = new Queue();
       myQ.Enqueue( "The" );
       myQ.Enqueue( "quick" );
       myQ.Enqueue( "brown" );
       myQ.Enqueue( "fox" );
       myQ.Enqueue( "jumped" );
 
       // Displays the count and values of the Queue.
       Console.WriteLine( "Initially," );
       Console.WriteLine( "   Count    : {0}", myQ.Count );
       Console.Write( "   Values:" );
       PrintValues( myQ );
 
       // Clears the Queue.
       myQ.Clear();
 
       // Displays the count and values of the Queue.
       Console.WriteLine( "After Clear," );
       Console.WriteLine( "   Count    : {0}", myQ.Count );
       Console.Write( "   Values:" );
       PrintValues( myQ );
    }
 
 
    public static void PrintValues( IEnumerable myCollection )  {
       System.Collections.IEnumerator myEnumerator = myCollection.GetEnumerator();
       while ( myEnumerator.MoveNext() )
          Console.Write( "\t{0}", myEnumerator.Current );
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 Initially,
    Count    : 5
    Values:    The    quick    brown    fox    jumped
 After Clear,
    Count    : 0
    Values:
 */ 

    
See also:
Queue.TrimToSize

Return to top


Method: Clone()
Summary
Creates a shallow copy of the Queue.
C# Syntax:
public virtual object Clone();
Return Value:
A shallow copy of the Queue.
Implements:
ICloneable.Clone
Remarks
A shallow copy of a collection copies only the elements of the collection, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new collection point to the same objects that the references in the original collection point to.

In contrast, a deep copy of a collection copies the elements and everything directly or indirectly referenced by the elements.

Return to top


Method: Contains(
   object obj
)
Summary
Determines whether an element is in the Queue.
C# Syntax:
public virtual bool Contains(
   object obj
);
Parameters:

obj

The Object to locate in the Queue. The element to locate can be null. The Object to locate in the Queue. The element to locate can be null.

Return Value:
true if obj is found in the Queue; otherwise, false.
Remarks
This method performs a linear search; therefore, the average execution time is proportional to Queue.Count. That is, this method is an O(n) operation, where n is Queue.Count.

This method determines equality by calling Object.Equals.

Return to top


Method: CopyTo(
   Array array,
   int index
)
Summary
Copies the Queue elements to an existing one-dimensional Array, starting at the specified array index.
C# Syntax:
public virtual void CopyTo(
   Array array,
   int index
);
Parameters:

array

The one-dimensional Array that is the destination of the elements copied from Queue. The Array must have zero-based indexing.

index

The zero-based index in array at which copying begins.

Exceptions
Exception Type Condition
ArgumentNullException array is null.
ArgumentOutOfRangeException index is less than zero.
ArgumentException array is multidimensional.

-or-

index is equal to or greater than the length of array.

-or-

The number of elements in the source Queue is greater than the available space from index to the end of the destination array.

ArrayTypeMismatchException The type of the source Queue cannot be cast automatically to the type of the destination array.
Implements:
ICollection.CopyTo
Remarks
The elements are copied to the Array in the same order in which the enumerator iterates through the Queue.
Example
The following example shows how to copy a Queue into a one-dimensional Array instance and into a one-dimensional standard array.
 using System;
 using System.Collections;
 public class SamplesQueue  {
 
    public static void Main()  {
 
       // Creates and initializes the source Queue.
       Queue mySourceQ = new Queue();
       mySourceQ.Enqueue( "three" );
       mySourceQ.Enqueue( "napping" );
       mySourceQ.Enqueue( "cats" );
       mySourceQ.Enqueue( "in" );
       mySourceQ.Enqueue( "the" );
       mySourceQ.Enqueue( "barn" );
 
       // Creates and initializes the one-dimensional target Array.
       Array myTargetArray=Array.CreateInstance( typeof(String), 15 );
       myTargetArray.SetValue( "The", 0 );
       myTargetArray.SetValue( "quick", 1 );
       myTargetArray.SetValue( "brown", 2 );
       myTargetArray.SetValue( "fox", 3 );
       myTargetArray.SetValue( "jumped", 4 );
       myTargetArray.SetValue( "over", 5 );
       myTargetArray.SetValue( "the", 6 );
       myTargetArray.SetValue( "lazy", 7 );
       myTargetArray.SetValue( "dog", 8 );
 
       // Displays the values of the target Array.
       Console.WriteLine( "The target Array contains the following (before and after copying):" );
       PrintValues( myTargetArray, ' ' );
 
       // Copies the entire source Queue to the target Array, starting at index 6.
       mySourceQ.CopyTo( myTargetArray, 6 );
 
       // Displays the values of the target Array.
       PrintValues( myTargetArray, ' ' );
 
       // Copies the entire source Queue to a new standard array.
       Object[] myStandardArray = mySourceQ.ToArray();
 
       // Displays the values of the new standard array.
       Console.WriteLine( "The new standard array contains the following:" );
       PrintValues( myStandardArray, ' ' );
    }
 
 
    public static void PrintValues( Array myArr, char mySeparator )  {
       System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
       int i = 0;
       int cols = myArr.GetLength( myArr.Rank - 1 );
       while ( myEnumerator.MoveNext() )  {
          if ( i < cols )  {
             i++;
          } else  {
             Console.WriteLine();
             i = 1;
          }
          Console.Write( "{0}{1}", mySeparator, myEnumerator.Current );
       }
       Console.WriteLine();
    }
 
    public static void PrintValues( Object[] myArr, char mySeparator )  {
       foreach ( Object myObj in myArr )  {
          Console.Write( "{0}{1}", mySeparator, myObj );
       }
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 The target Array contains the following (before and after copying):
  The quick brown fox jumped over the lazy dog      
  The quick brown fox jumped over three napping cats in the barn   
 The new standard array contains the following:
  three napping cats in the barn
 */ 

    

Return to top


Method: Dequeue()
Summary
Removes and returns the object at the beginning of the Queue.
C# Syntax:
public virtual object Dequeue();
Return Value:
The object that is removed from the beginning of the Queue.
Exceptions
Exception Type Condition
InvalidOperationException The Queue is empty.
Remarks
This method is similar to the Queue.Peek method, but Queue.Peek does not modify the Queue.

This method is an O(1) operation.

Example
The following example shows how to add elements to the Queue, remove elements from the Queue or just view the element at the beginning of the Queue.
 using System;
 using System.Collections;
 public class SamplesQueue  {
 
    public static void Main()  {
 
       // Creates and initializes a new Queue.
       Queue myQ = new Queue();
       myQ.Enqueue( "The" );
       myQ.Enqueue( "quick" );
       myQ.Enqueue( "brown" );
       myQ.Enqueue( "fox" );
 
       // Displays the Queue.
       Console.Write( "Queue values:" );
       PrintValues( myQ, '\t' );
 
       // Removes an element from the Queue.
       Console.WriteLine( "(Dequeue)\t{0}", myQ.Dequeue() );
 
       // Displays the Queue.
       Console.Write( "Queue values:" );
       PrintValues( myQ, '\t' );
 
       // Removes another element from the Queue.
       Console.WriteLine( "(Dequeue)\t{0}", myQ.Dequeue() );
 
       // Displays the Queue.
       Console.Write( "Queue values:" );
       PrintValues( myQ, '\t' );
 
       // Views the first element in the Queue but does not remove it.
       Console.WriteLine( "(Peek)   \t{0}", myQ.Peek() );
 
       // Displays the Queue.
       Console.Write( "Queue values:" );
       PrintValues( myQ, '\t' );
    }
 
 
    public static void PrintValues( IEnumerable myCollection, char mySeparator )  {
       System.Collections.IEnumerator myEnumerator = myCollection.GetEnumerator();
       while ( myEnumerator.MoveNext() )
          Console.Write( "{0}{1}", mySeparator, myEnumerator.Current );
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 Queue values:    The    quick    brown    fox
 (Dequeue)    The
 Queue values:    quick    brown    fox
 (Dequeue)    quick
 Queue values:    brown    fox
 (Peek)       brown
 Queue values:    brown    fox
 */ 

    
See also:
Queue.Enqueue | Queue.Peek

Return to top


Method: Enqueue(
   object obj
)
Summary
Adds an object to the end of the Queue.
C# Syntax:
public virtual void Enqueue(
   object obj
);
Parameters:

obj

The object to add to the Queue.

Remarks
If Queue.Count already equals the capacity of the Queue, the capacity is increased by automatically reallocating the internal array before copying the old elements and adding the new element. The new capacity is determined by multiplying the current capacity by the growth factor, which is determined when the Queue is constructed.

If Queue.Count is less than the capacity of the internal array, this method is an O(1) operation. If the internal array needs to be reallocated to accommodate the new element, this method becomes an O(n) operation, where n is Queue.Count.

Example
The following example shows how to add elements to the Queue, remove elements from the Queue or just view the element at the beginning of the Queue.
 using System;
 using System.Collections;
 public class SamplesQueue  {
 
    public static void Main()  {
 
       // Creates and initializes a new Queue.
       Queue myQ = new Queue();
       myQ.Enqueue( "The" );
       myQ.Enqueue( "quick" );
       myQ.Enqueue( "brown" );
       myQ.Enqueue( "fox" );
 
       // Displays the Queue.
       Console.Write( "Queue values:" );
       PrintValues( myQ, '\t' );
 
       // Removes an element from the Queue.
       Console.WriteLine( "(Dequeue)\t{0}", myQ.Dequeue() );
 
       // Displays the Queue.
       Console.Write( "Queue values:" );
       PrintValues( myQ, '\t' );
 
       // Removes another element from the Queue.
       Console.WriteLine( "(Dequeue)\t{0}", myQ.Dequeue() );
 
       // Displays the Queue.
       Console.Write( "Queue values:" );
       PrintValues( myQ, '\t' );
 
       // Views the first element in the Queue but does not remove it.
       Console.WriteLine( "(Peek)   \t{0}", myQ.Peek() );
 
       // Displays the Queue.
       Console.Write( "Queue values:" );
       PrintValues( myQ, '\t' );
    }
 
 
    public static void PrintValues( IEnumerable myCollection, char mySeparator )  {
       System.Collections.IEnumerator myEnumerator = myCollection.GetEnumerator();
       while ( myEnumerator.MoveNext() )
          Console.Write( "{0}{1}", mySeparator, myEnumerator.Current );
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 Queue values:    The    quick    brown    fox
 (Dequeue)    The
 Queue values:    quick    brown    fox
 (Dequeue)    quick
 Queue values:    brown    fox
 (Peek)       brown
 Queue values:    brown    fox
 */ 

    
See also:
Queue.Dequeue | Queue.Peek

Return to top


Method: Equals(
   object obj
)
Inherited
See base class member description: System.Object.Equals
C# Syntax:
public virtual bool Equals(
   object obj
);

For more information on members inherited from System.Object click on the link above.

Return to top


Method: Finalize()
Inherited
See base class member description: System.Object.Finalize
C# Syntax:
~Queue();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetEnumerator()
Summary
Returns an enumerator that can iterate through the Queue.
C# Syntax:
public virtual IEnumerator GetEnumerator();
Return Value:
An IEnumerator for the Queue.
Implements:
IEnumerable.GetEnumerator
Remarks
Enumerators only allow reading the data in the collection. Enumerators cannot be used to modify the underlying collection.

Initially, the enumerator is positioned before the first element in the collection. IEnumerator.Reset also brings the enumerator back to this position. At this position, calling IEnumerator.Current throws an exception. Therefore, you must call IEnumerator.MoveNext to advance the enumerator to the first element of the collection before reading the value of IEnumerator.Current.

IEnumerator.Current returns the same object until either IEnumerator.MoveNext or IEnumerator.Reset is called. IEnumerator.MoveNext sets IEnumerator.Current to the next element.

After the end of the collection is passed, the enumerator is positioned after the last element in the collection, and calling IEnumerator.MoveNext returns false. If the last call to IEnumerator.MoveNext returned false, calling IEnumerator.Current throws an exception. To set IEnumerator.Current to the first element of the collection again, you can call IEnumerator.Reset followed by IEnumerator.MoveNext.

An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying or deleting elements, the enumerator is irrecoverably invalidated and the next call to IEnumerator.MoveNext or IEnumerator.Reset throws an InvalidOperationException. If the collection is modified between IEnumerator.MoveNext and IEnumerator.Current, IEnumerator.Current will return the element that it is set to, even if the enumerator is already invalidated.

The enumerator does not have exclusive access to the collection; therefore, enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

See also:
IEnumerator

Return to top


Method: GetHashCode()
Inherited
See base class member description: System.Object.GetHashCode
C# Syntax:
public virtual int GetHashCode();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetType()
Inherited
See base class member description: System.Object.GetType
C# Syntax:
public Type GetType();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: MemberwiseClone()
Inherited
See base class member description: System.Object.MemberwiseClone
C# Syntax:
protected object MemberwiseClone();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: Peek()
Summary
Returns the object at the beginning of the Queue without removing it.
C# Syntax:
public virtual object Peek();
Return Value:
The object at the beginning of the Queue.
Exceptions
Exception Type Condition
InvalidOperationException The Queue is empty.
Remarks
This method is similar to the Queue.Dequeue method, but Queue.Peek does not modify the Queue.
Example
The following example shows how to add elements to the Queue, remove elements from the Queue or just view the element at the beginning of the Queue.
 using System;
 using System.Collections;
 public class SamplesQueue  {
 
    public static void Main()  {
 
       // Creates and initializes a new Queue.
       Queue myQ = new Queue();
       myQ.Enqueue( "The" );
       myQ.Enqueue( "quick" );
       myQ.Enqueue( "brown" );
       myQ.Enqueue( "fox" );
 
       // Displays the Queue.
       Console.Write( "Queue values:" );
       PrintValues( myQ, '\t' );
 
       // Removes an element from the Queue.
       Console.WriteLine( "(Dequeue)\t{0}", myQ.Dequeue() );
 
       // Displays the Queue.
       Console.Write( "Queue values:" );
       PrintValues( myQ, '\t' );
 
       // Removes another element from the Queue.
       Console.WriteLine( "(Dequeue)\t{0}", myQ.Dequeue() );
 
       // Displays the Queue.
       Console.Write( "Queue values:" );
       PrintValues( myQ, '\t' );
 
       // Views the first element in the Queue but does not remove it.
       Console.WriteLine( "(Peek)   \t{0}", myQ.Peek() );
 
       // Displays the Queue.
       Console.Write( "Queue values:" );
       PrintValues( myQ, '\t' );
    }
 
 
    public static void PrintValues( IEnumerable myCollection, char mySeparator )  {
       System.Collections.IEnumerator myEnumerator = myCollection.GetEnumerator();
       while ( myEnumerator.MoveNext() )
          Console.Write( "{0}{1}", mySeparator, myEnumerator.Current );
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 Queue values:    The    quick    brown    fox
 (Dequeue)    The
 Queue values:    quick    brown    fox
 (Dequeue)    quick
 Queue values:    brown    fox
 (Peek)       brown
 Queue values:    brown    fox
 */ 

    
See also:
Queue.Enqueue | Queue.Dequeue

Return to top


Method: Synchronized(
   Queue queue
)
Summary
Returns a Queue wrapper that is synchronized (thread-safe).
C# Syntax:
public static Queue Synchronized(
   Queue queue
);
Parameters:

queue

The Queue to synchronize.

Return Value:
A Queue wrapper that is synchronized (thread-safe).
Exceptions
Exception Type Condition
ArgumentNullException queue is null.
Remarks
To guarantee the thread safety of the Queue, all operations must be done through this wrapper only.

Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

The following code example shows how to lock the collection using the Queue.SyncRoot during the entire enumeration:

              Queue myCollection = new Queue();
               lock( myCollection.SyncRoot ) {
               foreach ( Object item in myCollection ) {
               // Insert your code here.
               }
              }
            
Example
The following example shows how to synchronize a Queue, determine if a Queue is synchronized and use a synchronized Queue.
 using System;
 using System.Collections;
 public class SamplesQueue  {
 
    public static void Main()  {
 
       // Creates and initializes a new Queue.
       Queue myQ = new Queue();
       myQ.Enqueue( "The" );
       myQ.Enqueue( "quick" );
       myQ.Enqueue( "brown" );
       myQ.Enqueue( "fox" );
 
       // Creates a synchronized wrapper around the Queue.
       Queue mySyncdQ = Queue.Synchronized( myQ );
 
       // Displays the sychronization status of both Queues.
       Console.WriteLine( "myQ is {0}.", myQ.IsSynchronized ? "synchronized" : "not synchronized" );
       Console.WriteLine( "mySyncdQ is {0}.", mySyncdQ.IsSynchronized ? "synchronized" : "not synchronized" );
    }
 }
 /* 
 This code produces the following output.
 
 myQ is not synchronized.
 mySyncdQ is synchronized.
 */ 

    
See also:
Queue.IsSynchronized | Queue.SyncRoot

Return to top


Method: ToArray()
Summary
Copies the Queue elements to a new array.
C# Syntax:
public virtual object[] ToArray();
Return Value:
A new array containing elements copied from the Queue.
Remarks
The Queue is not modified. The order of the elements in the new array is the same as the order of the elements from the beginning of the Queue to its end.
Example
The following example shows how to copy a Queue into a one-dimensional Array instance and into a one-dimensional standard array.
 using System;
 using System.Collections;
 public class SamplesQueue  {
 
    public static void Main()  {
 
       // Creates and initializes the source Queue.
       Queue mySourceQ = new Queue();
       mySourceQ.Enqueue( "three" );
       mySourceQ.Enqueue( "napping" );
       mySourceQ.Enqueue( "cats" );
       mySourceQ.Enqueue( "in" );
       mySourceQ.Enqueue( "the" );
       mySourceQ.Enqueue( "barn" );
 
       // Creates and initializes the one-dimensional target Array.
       Array myTargetArray=Array.CreateInstance( typeof(String), 15 );
       myTargetArray.SetValue( "The", 0 );
       myTargetArray.SetValue( "quick", 1 );
       myTargetArray.SetValue( "brown", 2 );
       myTargetArray.SetValue( "fox", 3 );
       myTargetArray.SetValue( "jumped", 4 );
       myTargetArray.SetValue( "over", 5 );
       myTargetArray.SetValue( "the", 6 );
       myTargetArray.SetValue( "lazy", 7 );
       myTargetArray.SetValue( "dog", 8 );
 
       // Displays the values of the target Array.
       Console.WriteLine( "The target Array contains the following (before and after copying):" );
       PrintValues( myTargetArray, ' ' );
 
       // Copies the entire source Queue to the target Array, starting at index 6.
       mySourceQ.CopyTo( myTargetArray, 6 );
 
       // Displays the values of the target Array.
       PrintValues( myTargetArray, ' ' );
 
       // Copies the entire source Queue to a new standard array.
       Object[] myStandardArray = mySourceQ.ToArray();
 
       // Displays the values of the new standard array.
       Console.WriteLine( "The new standard array contains the following:" );
       PrintValues( myStandardArray, ' ' );
    }
 
 
    public static void PrintValues( Array myArr, char mySeparator )  {
       System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
       int i = 0;
       int cols = myArr.GetLength( myArr.Rank - 1 );
       while ( myEnumerator.MoveNext() )  {
          if ( i < cols )  {
             i++;
          } else  {
             Console.WriteLine();
             i = 1;
          }
          Console.Write( "{0}{1}", mySeparator, myEnumerator.Current );
       }
       Console.WriteLine();
    }
 
    public static void PrintValues( Object[] myArr, char mySeparator )  {
       foreach ( Object myObj in myArr )  {
          Console.Write( "{0}{1}", mySeparator, myObj );
       }
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 The target Array contains the following (before and after copying):
  The quick brown fox jumped over the lazy dog      
  The quick brown fox jumped over three napping cats in the barn   
 The new standard array contains the following:
  three napping cats in the barn
 */ 

    

Return to top


Method: ToString()
Inherited
See base class member description: System.Object.ToString
C# Syntax:
public virtual string ToString();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: TrimToSize()
Summary
Sets the capacity to the actual number of elements in the Queue.
C# Syntax:
public virtual void TrimToSize();
Exceptions
Exception Type Condition
NotSupportedException The Queue is read-only.
Remarks
This method can be used to minimize a list's memory overhead if no new elements will be added to the list.

To completely clear all elements in a list, call the Queue.Clear method before calling Queue.TrimToSize. Trimming an empty Queue sets the capacity of the Queue to the default capacity, not zero.

See also:
Queue.Clear | Queue.Count

Return to top


Top of page

Copyright (c) 2002 Microsoft Corporation. All rights reserved.