Queue.Synchronized() In C#

The Queue.Synchronized function in C# belongs to the System.Collections namespace. It constructs a synchronized wrapper around a standard Queue object, ensuring thread safety. This feature proves particularly valuable in scenarios with multiple threads operating on a shared Queue simultaneously.

Syntax:

It has the following syntax:

Example

Queue myQueue = new Queue();
Queue synchronizedQueue = Queue.Synchronized(myQueue);

You can ensure thread safety for the Queue object by wrapping it with synchronization. This synchronized wrapper provides a thread-safe environment for the specified Queue without requiring manual locking in a multi-threaded setup.

To address the risk of data corruption or unexpected behavior, synchronization mechanisms are implemented to restrict simultaneous data access to a single thread. This approach involves generating a synchronized wrapper for the specified queue instance or object. The wrapper guarantees that every action performed on the Queue is indivisible and secure for multiple threads, preventing any other thread from interacting with the Queue while an operation is in progress. This synchronized Queue is suitable for utilization in a multi-threaded environment without the need for extra locks or synchronization techniques.

Operations like "Enqueue" and "Dequeue" are carried out in a manner that ensures thread safety. The synchronization is implemented at the level of individual method invocations, safeguarding each operation from being disrupted by other threads. It should be noted that this approach does not guarantee atomicity for combined operations. If there is a necessity to execute multiple operations as a single atomic operation, additional synchronization mechanisms should be employed or alternatively, consider utilizing collections from the System.Collections.Concurrent namespace, specifically designed for concurrent access. This technique is found within the conventional collection classes in C#, with contemporary C# code frequently opting for concurrent collections to enhance performance in scenarios involving multiple threads.

Example:

Let's consider a code example to demonstrate the Queue.Synchronized method in C#.

Example

using System;
using System.Collections;
class Program{
 static void Main(){
 Queue myQueue = new Queue();
 // Synchronize the Queue
 Queue synchronizedQueue = Queue.Synchronized(myQueue);
 // Add items to the synchronized queue
 synchronizedQueue.Enqueue("Item 1");
 synchronizedQueue.Enqueue("Item 2");
 synchronizedQueue.Enqueue("Item 3");
 // Dequeue items from the synchronized queue
 while (synchronizedQueue.Count > 0){
 object item = synchronizedQueue.Dequeue();
 Console.WriteLine($"Dequeued: {item}");
 }
 }
}

Output:

The <style> code snippet below showcases a diagram with a specific styling:

Example

.placeholder-diagram { background: linear-gradient(135deg, #374151 0%, #1f2937 100%); border-radius: 12px; padding: 40px; margin: 20px 0; text-align: center; }
.placeholder-diagram .placeholder-icon { font-size: 3rem; margin-bottom: 10px; }
.placeholder-diagram .placeholder-text { color: #9ca3af; font-size: 1rem; }

Explanation:

The process begins with importing the required libraries. A Queue named myQueue is declared and initialized as a new instance of the Queue class. This myQueue instance functions as a non-thread-safe Queue. To address this, a synchronized wrapper is generated around myQueue using the Queue.Synchronized method, transforming it into a thread-safe queue. This modification allows multiple threads to access myQueue concurrently without risking data corruption or unexpected outcomes. Subsequently, three items are added to the synchronized Queue through the Enqueue operation. A while loop is then employed to extract items from the Queue, iterating as long as there are items present in the synchronized Queue. Utilizing the Count property provides the total count of elements within the Queue. Following this, the Dequeue operation eliminates and returns the object at the Queue's beginning, displaying the dequeued item on the console. These queue operations are safeguarded for multi-threaded environments. In the absence of synchronization, concurrent access by multiple threads might result in unpredictable and erroneous behavior. By employing the synchronized wrapper, data integrity is maintained, ensuring proper synchronization among threads when interacting with the shared Queue.

Example:

Let's consider a C# code example to illustrate the Queue.Synchronized method.

Example

using System;
using System.Collections;
using System.Threading;
using System.Threading.Tasks;
class TicketCounter
{
 static Queue synchronizedQueue;

 static void Main()
 {
 // Create a regular Queue to represent the ticket queue
 Queue ticketQueue = new Queue();

 // Use Queue.Synchronized() to make it thread-safe
 synchronizedQueue = Queue.Synchronized(ticketQueue);

 // Simulate multiple people buying tickets concurrently
 Task[] tasks = new Task[5];

 for (int i = 0; i < tasks.Length; i++)
 {
 int personNumber = i + 1;
 tasks[i] = Task.Run(() => BuyTicket(personNumber));
 }

 // Wait for all tasks to complete
 Task.WaitAll(tasks);

 Console.WriteLine("All tickets sold. Queue is empty.");
 }

 static void BuyTicket(int personNumber)
 {
 // Simulate a person buying a ticket
 Thread.Sleep(100); // Simulate some processing time

 // Enqueue the person to the synchronized ticket queue
 synchronizedQueue.Enqueue($"Person {personNumber}");

 Console.WriteLine($"Person {personNumber} bought a ticket. Queue size: {synchronizedQueue.Count}");

 // Simulate additional processing after buying a ticket
 Thread.Sleep(200); // Simulate some additional processing time

 // Dequeue the person from the synchronized ticket queue
 string person = (string)synchronizedQueue.Dequeue();
 Console.WriteLine($"Person {person} left the counter. Queue size: {synchronizedQueue.Count}");
 }
}

Output:

The styling for the placeholder includes a linear gradient background, border radius, padding, margin, and center alignment. The placeholder also features an icon with a font size of 3rem and text with a color of #9ca3af and font size of 1rem.

Explanation:

The software application simulates a ticket booth scenario, with a standard line representing the ticket queue. Implementing Queue operations guarantees secure thread handling in a multi-threaded setup. By utilizing a synchronized method, a synchronized queue is established to maintain data integrity during concurrent ticket transactions. Tasks are employed to mimic simultaneous ticket purchases by various individuals. The synchronized Queue facilitates organized access, averting any potential data corruption during parallel activities. Each task adds customers to the Queue, showcasing successful ticket acquisitions. Delays between actions demonstrate the program's ability to handle threads securely. Once all tasks are finished, a notification confirms the sell-out status and the synchronized queue being empty.

Input Required

This code uses input(). Please provide values below: