Open In App

How to get Synchronize access to the Queue in C#

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:



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.




// C# program to illustrate the
// use of SyncRoot property of
// the Queue
using System;
using System.Threading;
using System.Collections;
  
namespace sync_root {
  
class GFG {
  
    // Main Method
    static void Main(string[] args)
    {
  
        // Declaring an Queue
        Queue q1 = new Queue();
  
        // Adding elements to Queue
        q1.Enqueue(1);
        q1.Enqueue(2);
        q1.Enqueue(3);
        q1.Enqueue(4);
        q1.Enqueue(5);
  
        // Using the SyncRoot property
        lock(q1.SyncRoot)
        {
            // foreach loop to display
            // the elements in q1
            foreach(Object i in q1)
                Console.WriteLine(i);
        }
    }
}
}

Output:
1
2
3
4
5

Example 2:




// C# program to illustrate the
// use of SyncRoot property of
// the Queue
using System;
using System.Threading;
using System.Collections;
  
namespace sync_root {
  
class GFG {
  
    // Main Method
    static void Main(string[] args)
    {
  
        // Declaring an Queue
        Queue q1 = new Queue();
  
        // Adding elements to Queue
        q1.Enqueue("C");
        q1.Enqueue("C++");
        q1.Enqueue("Java");
        q1.Enqueue("C#");
        q1.Enqueue("HTML");
  
        // Using the SyncRoot property
        lock(q1.SyncRoot)
        {
            // foreach loop to display
            // the elements in q1
            foreach(Object i in q1)
                Console.WriteLine(i);
        }
    }
}
}

Output:
C
C++
Java
C#
HTML

Reference:


Article Tags :
C#