Open In App

Queue.Synchronized() Method in C#

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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:




// 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");
    }
}


Output:

myQueue is Not Synchronized.
sq is Synchronized.

Example 2:




// 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);
    }
}


Runtime Error:

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

Reference:



Last Updated : 04 Feb, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads