Open In App

Queue.IsSynchronized Property in C#

Last Updated : 04 Feb, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report
This property is used get a value which indicates whether access to the Queue is synchronized (thread safe) or not. Syntax:
public virtual bool IsSynchronized { get; }
Property Value: This property returns true if access to the Queue is synchronized(thread safe) otherwise, false. The default is false. Below programs illustrate the use of the above-discussed property: Example 1: csharp
// C# code to illustrate the
// Queue.IsSynchronized Property
using System;
using System.Collections;

class GFG {

    // Driver code
    public static void Main()
    {

        // Creating a Queue
        Queue myQueue = new Queue();

        // Inserting the elements into the Queue
        myQueue.Enqueue("C");
        myQueue.Enqueue("C++");
        myQueue.Enqueue("Java");
        myQueue.Enqueue("C#");
        myQueue.Enqueue("HTML");
        myQueue.Enqueue("CSS");

        // Creates a synchronized
        // wrapper around the Queue
        Queue sq = Queue.Synchronized(myQueue);

        // Displays the synchronization
        // status of both Queue
        Console.WriteLine("myQueue is {0}.", myQueue.IsSynchronized ?
                                "Synchronized" : "Not Synchronized");

        Console.WriteLine("sq is {0}.", sq.IsSynchronized ? 
                       "Synchronized" : "Not Synchronized");
    }
}
Output:
myQueue is Not Synchronized.
sq is Synchronized.
Example 2: csharp
// C# code to check if Queue
// Is Synchronized or not
using System;
using System.Collections;

class GFG {

    // Driver code
    public static void Main()
    {

        // Creating a Queue
        Queue myQueue = new Queue();

        // Inserting the elements into the Queue
        myQueue.Enqueue(1);
        myQueue.Enqueue(2);
        myQueue.Enqueue(3);
        myQueue.Enqueue(4);

        // the default is false for
        // IsSynchronized property
        Console.WriteLine(myQueue.IsSynchronized);
    }
}
Output:
False
Note:
  • Retrieving the value of this property is an O(1) operation.
  • To guarantee the thread safety of the Queue, all operations must be done through the wrapper returned by the Synchronized method.
  • Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception.
Reference:

Next Article

Similar Reads