How to get Synchronize access to the Stack in C# (original) (raw)

Last Updated : 18 Feb, 2019

Stack.SyncRoot Property is used to get an object which can be used to synchronize access to the Stack. Stack represents last-in, first out collection of object. It is used when you need last-in, first-out access to items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item. This class comes under System.Collections namespace.

Syntax: public virtual object SyncRoot { get; }Property Value: An object which can be used to synchronize access to the Stack.

Important Points:

Below programs illustrate the use of the above-discussed property:Example 1: In this code, we are using SyncRoot to get Synchronized access to the Stack named st, which is not a thread-safe procedure and can cause an exception. So to avoid the exception we lock the collection during the enumeration.

csharp `

// C# program to illustrate the // use of SyncRoot property of // the Stack using System; using System.Threading; using System.Collections;

namespace sync_root {

class GFG {

// Main Method
static void Main(string[] args)
{

    // Declaring an Stack
    Stack st = new Stack();

    // Adding elements to Stack
    st.Push(1);
    st.Push(2);
    st.Push(3);
    st.Push(4);
    st.Push(5);

    // Using the SyncRoot property
    lock(st.SyncRoot)
    {
        // foreach loop to display
        // the elements in st
        foreach(Object i in st)
            Console.WriteLine(i);
    }
}

} }

`

Example 2:

csharp `

// C# program to illustrate the // use of SyncRoot property of // the Stack using System; using System.Threading; using System.Collections;

namespace sync_root {

class GFG {

// Main Method
static void Main(string[] args)
{

    // Declaring an Stack
    Stack st = new Stack();

    // Adding elements to Stack
    st.Push("C");
    st.Push("C++");
    st.Push("Java");
    st.Push("C#");
    st.Push("HTML");

    // Using the SyncRoot property
    lock(st.SyncRoot)
    {
        // foreach loop to display
        // the elements in st
        foreach(Object i in st)
            Console.WriteLine(i);
    }
}

} }

`

Output:

HTML C# Java C++ C

Reference: