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:
using System;
using System.Collections;
class GFG {
public static void Main()
{
Queue myQueue = new Queue();
myQueue.Enqueue( "C" );
myQueue.Enqueue( "C++" );
myQueue.Enqueue( "Java" );
myQueue.Enqueue( "C#" );
myQueue.Enqueue( "HTML" );
myQueue.Enqueue( "CSS" );
Queue sq = Queue.Synchronized(myQueue);
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:
using System;
using System.Collections;
class GFG {
public static void Main()
{
Queue myQueue = new Queue();
myQueue.Enqueue( "Geeks" );
myQueue.Enqueue( "for" );
myQueue.Enqueue( "Geeks" );
myQueue.Enqueue( "Noida" );
myQueue.Enqueue( "Sector" );
myQueue.Enqueue( "142" );
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
Share your thoughts in the comments
Please Login to comment...