How to get Synchronize access to an Array in C#?

CsharpServer Side ProgrammingProgramming

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

Example

 Live Demo

using System;
public class Demo {
   public static void Main() {
      Array intArr = new int[] {5, 10, 15, 20, 25, 30, 35, 40 };
      Console.WriteLine("Integer array...");
      foreach (int i in intArr)
      Console.WriteLine(i);
      Console.WriteLine("After applying lock on array...");
      lock(intArr.SyncRoot) {
         foreach (Object ob in intArr)
         Console.WriteLine(ob);
      }
   }
}

Output

This will produce the following output −

Integer array...
5
10
15
20
25
30
35
40
After applying lock on array...
5
10
15
20
25
30
35
40

Example

Let us see another example −

 Live Demo

using System;
public class Demo {
   public static void Main() {
      Array strArr = new String[] {"Harry", "Tom", "Kevin", "Ryan", "Katie", "Amy" };
      Console.WriteLine("String array...");
      foreach (string i in strArr)
      Console.WriteLine(i);
      Console.WriteLine("After applying lock on array...");
      lock(strArr.SyncRoot) {
         foreach (Object ob in strArr)
         Console.WriteLine(ob);
      }
   }
}

Output

This will produce the following output −

String array...
Harry
Tom
Kevin
Ryan
Katie
Amy
After applying lock on array...
Harry
Tom
Kevin
Ryan
Katie
Amy
raja
Published on 16-Dec-2019 06:31:29
Advertisements