Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Queue.IsSynchronized Property in C#
The Queue.IsSynchronized property in C# is used to determine whether access to the Queue is synchronized, meaning it is thread-safe for concurrent access by multiple threads.
Syntax
Following is the syntax for the IsSynchronized property −
public virtual bool IsSynchronized { get; }
Return Value
The property returns a bool value −
true − if access to the Queue is synchronized (thread-safe)
false − if access to the Queue is not synchronized
Using IsSynchronized with Regular Queue
By default, a regular Queue is not synchronized and returns false for the IsSynchronized property −
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);
queue.Enqueue(400);
queue.Enqueue(500);
Console.WriteLine("Queue elements:");
IEnumerator demoEnum = queue.GetEnumerator();
while (demoEnum.MoveNext()) {
Console.WriteLine(demoEnum.Current);
}
Console.WriteLine("Is Queue synchronized? = " + queue.IsSynchronized);
}
}
The output of the above code is −
Queue elements: 100 200 300 400 500 Is Queue synchronized? = False
Using Queue.Synchronized() Method
To create a synchronized version of a Queue, you can use the Queue.Synchronized() method. The synchronized queue will return true for the IsSynchronized property −
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");
Console.WriteLine("Original Queue elements:");
IEnumerator demoEnum = queue.GetEnumerator();
while (demoEnum.MoveNext()) {
Console.WriteLine(demoEnum.Current);
}
Console.WriteLine("Is original Queue synchronized? = " + queue.IsSynchronized);
Queue syncQueue = Queue.Synchronized(queue);
Console.WriteLine("Is synchronized Queue thread-safe? = " + syncQueue.IsSynchronized);
}
}
The output of the above code is −
Original Queue elements: AB BC CD DE Is original Queue synchronized? = False Is synchronized Queue thread-safe? = True
Thread Safety Comparison
| Queue Type | IsSynchronized Value | Thread Safety |
|---|---|---|
| Regular Queue | false | Not thread-safe |
| Queue.Synchronized(queue) | true | Thread-safe |
Conclusion
The IsSynchronized property helps you determine if a Queue instance is thread-safe. Regular queues return false, while queues created with Queue.Synchronized() return true, indicating they can be safely accessed by multiple threads concurrently.
