How to get Synchronize access to the Stack in C#?

CsharpServer Side ProgrammingProgramming

To get synchronize access to the Stack, the code is as follows −

Example

 Live Demo

using System;
using System.Collections;
public class Demo {
   public static void Main() {
      Stack stack = new Stack();
      stack.Push(100);
      stack.Push(200);
      stack.Push(300);
      stack.Push(400);
      stack.Push(500);
      Console.WriteLine("Stack...");
      foreach(Object ob in stack) {
         Console.WriteLine(ob);
      }
      Console.WriteLine("Count of elements = "+stack.Count);      
      Console.WriteLine("Synchronize access...");
      lock(stack.SyncRoot) {
         foreach(Object ob in stack) {
            Console.WriteLine(ob);
         }
      }
   }
}

Output

This will produce the following output −

Stack...
500
400
300
200
100
Count of elements = 5
Synchronize access...
500
400
300
200
100

Let us now see another example −

Example

 Live Demo

using System;
using System.Collections;
public class Demo {
   public static void Main() {
      Stack stack = new Stack();
      stack.Push("Jacob");
      stack.Push("Tim");
      stack.Push("Philips");
      stack.Push("Tom");
      stack.Push("Amy");
      stack.Push("Katie");
      stack.Push("Selena");
      stack.Push("Taylor");
      stack.Push("Justin");
      Console.WriteLine("Stack...");
      foreach(Object ob in stack) {
         Console.WriteLine(ob);
      }
      Console.WriteLine("\nSynchronize access...");
      lock(stack.SyncRoot) {
         foreach(Object ob in stack) {
            Console.WriteLine(ob);
         }
      }
   }
}

Output

This will produce the following output −

Stack...
Justin
Taylor
Selena
Katie
Amy
Tom
Philips
Tim
Jacob

Synchronize access...
Justin
Taylor
Selena
Katie
Amy
Tom
Philips
Tim
Jacob
raja
Published on 16-Dec-2019 07:20:12
Advertisements