VOOZH about

URL: https://www.geeksforgeeks.org/c-sharp/how-to-get-synchronize-access-to-the-queue-in-c-sharp/

⇱ How to get Synchronize access to the Queue in C# - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to get Synchronize access to the Queue in C#

Last Updated : 11 Jul, 2025
Queue.SyncRoot Property is used to get an object which can be used to synchronize access to the Queue. Queue represents a first-in, first out collection of object. It is used when you need first-in, first-out access of items. When you add an item in the list, it is called enqueue, and when you remove an item, it is called dequeue. This class comes under System.Collections namespace and implements ICollection, IEnumerable, and ICloneable interfaces. Important Points:
  • Synchronization of an object is done so that only one thread can manipulate the data in the Queue.
  • A property is a member of a class that provides a means for reading, writing and computing private data fields.
  • The synchronizing code cannot directly perform on the collection, so it must perform operations on the SyncRoot of the collection in order to guarantee the proper operation of collections that are derived from other objects.
  • Retrieving the value of this property is an O(1) operation.
Syntax: public virtual object SyncRoot { get; } Property Value: An object that can be used to synchronize access to the Queue.
Example 1: In this code, we are using SyncRoot to get Synchronized access to the Queue named q1, which is not a thread-safe procedure and can cause an exception. So to avoid the exception we lock the collection during the enumeration.
Output:
1
2
3
4
5
Example 2:
Comment

Explore