Queue.Synchronized() Method in C#


The Queue.Synchronized() method in C# is used to return a new Queue that wraps the original queue and is thread-safe.

Syntax

The syntax is as follows −

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

Above, the parameter queue is the queue to synchronize.

Example

Let us now see an example −

 Live Demo

using System;
using System.Collections;
public class Demo {
   public static void Main(){
      Queue queue = new Queue();
      queue.Enqueue("AB");
      queue.Enqueue("BC");
      queue.Enqueue("CD");
      queue.Enqueue("DE");
      queue.Enqueue("EF");
      queue.Enqueue("FG");
      queue.Enqueue("GH");
      queue.Enqueue("HI");
      Console.WriteLine("Queue...");
      IEnumerator demoEnum = queue.GetEnumerator();
      while (demoEnum.MoveNext()){
         Console.WriteLine(demoEnum.Current);
      }
      Console.WriteLine("Is Queue synchronized? = "+queue.IsSynchronized);
      Queue queue2 = Queue.Synchronized(queue);
      Console.WriteLine("Is Queue synchronized now? = "+queue2.IsSynchronized);
   }
}

Output

This will produce the following output −

Queue...
AB
BC
CD
DE
EF
FG
GH
HI
Is Queue synchronized? = False
Is Queue synchronized now? = True

Example

Let us now see another example −

 Live Demo

using System;
using System.Collections;
public class Demo {
   public static void Main(){
      Queue queue = new Queue();
      queue.Enqueue(100);
      queue.Enqueue(200);
      queue.Enqueue(300);
      Console.WriteLine("Is Queue synchronized? = "+queue.IsSynchronized);
      Queue queue2 = Queue.Synchronized(queue);
      Console.WriteLine("Is Queue synchronized now? = "+queue2.IsSynchronized);
      Console.Write("Count of elements = ");
      Console.WriteLine(queue.Count);
      Console.WriteLine("Queue...");
      foreach(int i in queue){
         Console.WriteLine(i);
      }
      Console.WriteLine("Does the queue has element 500? = "+queue.Contains(500));
      int[] intArr = new int[5];
      intArr[0] = 1;
      intArr[1] = 2;
      intArr[2] = 3;
      intArr[3] = 4;
      queue.CopyTo(intArr, 1);
      Console.WriteLine("\nQueue (Updated)");
      foreach(int i in queue){
         Console.WriteLine(i);
      }
      Console.WriteLine("\nArray (Updated)");
      foreach(int i in intArr){
         Console.WriteLine(i);
      }
   }
}

Output

This will produce the following output −

Is Queue synchronized? = False
Is Queue synchronized now? = True
Count of elements = 3
Queue...
100
200
300
Does the queue has element 500? = False
Queue (Updated)
100
200
300
Array (Updated)
1
100
200
300
0
raja
Published on 03-Dec-2019 07:29:19
Advertisements