What does Array.SyncRoot property of array class do in C#?

CsharpProgrammingServer Side Programming

The Array.SyncRoot property is used to get an object that can be used to synchronize access to the Array. The classes that have arrays can also use the SyncRoot property to implement their own synchronization.

Enumerating through a collection is not a thread safe procedure. The other threads may modify the collection even when the collection is synchronized. This would eventually cause the enumerator to throw an exception. For this, you need to lock the collection.

Let us see an example to work with Array.SyncRoot property −

Example

 Live Demo

using System;
using System.Collections.Generic;
using System.Linq;

class Program {
   static void Main() {
      Array arr = new int[] { 23, 11, 32, 18, 87 };
      lock(arr.SyncRoot) {
         foreach (Object val in arr)
         Console.WriteLine(val);
      }
   }
}

Output

23
11
32
18
87

Above, we have set a lock on the array −

lock(arr.SyncRoot)
raja
Published on 10-Aug-2018 08:26:37
Advertisements