Queue.Synchronized() Method in C#

This method is used to return a new Queue that wraps the original queue and is thread-safe. The wrapper returned by this method locks the queue before an operation is performed so that it is performed in a thread-safe manner.

Syntax:

public static System.Collections.Queue Synchronized (System.Collections.Queue queue);



Return Value: A Queue wrapper that is synchronized (thread safe).

Exception: This method will give ArgumentNullException if the queue is null.

Below programs illustrate the use of above-discussed method:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to illustrate the
// Queue.Synchronized() Method
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 ArrayList
        Console.WriteLine("myQueue is {0}.", myQueue.IsSynchronized ?
                                "Synchronized" : "Not Synchronized");
  
        Console.WriteLine("sq is {0}.", sq.IsSynchronized ? 
                      "Synchronized" : "Not Synchronized");
    }
}

chevron_right


Output:

myQueue is Not Synchronized.
sq is Synchronized.

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to illustrate the
// Queue.Synchronized() Method
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("Geeks");
        myQueue.Enqueue("for");
        myQueue.Enqueue("Geeks");
        myQueue.Enqueue("Noida");
        myQueue.Enqueue("Sector");
        myQueue.Enqueue("142");
  
        // it will give error as
        // the parameter is null
        Queue smyList = Queue.Synchronized(null);
    }
}

chevron_right


Runtime Error:

Unhandled Exception:
System.ArgumentNullException: Value cannot be null.
Parameter name: queue

Reference:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.