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


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("
Synchronize 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

Updated on: 16-Dec-2019

48 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements