- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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 −
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("
Queue (Updated)"); foreach(int i in queue){ Console.WriteLine(i); } Console.WriteLine("
Array (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
Advertisements