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:
// 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:
Recommended Posts:
- Difference between Method Overriding and Method Hiding in C#
- C# | Math.Abs() Method | Set - 2
- C# | Math.Sin() Method
- C# | SortedDictionary.Add() Method
- C# | Math.Cos() Method
- C# | Math.Tan() Method
- Anonymous Method in C#
- C# | Uri.IsHexEncoding() Method
- C# | String.Contains() Method
- C# | Uri.IsWellFormedOriginalString() Method
- C# | Uri.ToString() Method
- C# | Math.Min() Method
- C# | CompareOrdinal() Method
- C# | Method Parameters
- TimeSpan.Add() Method in C#
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.



