A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/c-sharp/how-to-get-synchronize-access-to-the-array-in-c-sharp/ below:

How to get Synchronize access to the Array in C#

How to get Synchronize access to the Array in C#

Last Updated : 11 Jul, 2025

Array.SyncRoot Property

is used to get an object that can be used to synchronize access to the Array. An

array

is a group of like-typed variables that are referred to by a common name.

Array class

comes under the

System

namespace.

Important Points:
Syntax: arrayName.SyncRoot Property Value: An object that can be used to synchronize access to the Array.
Example 1:

In this code, we are using SyncRoot to get Synchronized access to the Array named

arr

, 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
using System;
using System.Threading;
using System.Collections;

namespace sync_root {

class GFG {

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

        // Declaring an array
        Array arr = new int[] {12, 15, 20, 3, 6};

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

In the below example we use SynRoot property with an array of objects of class X.

csharp
// C# program to depict the use
// of SyncRoot Property
// for an array of objects
using System;
using System.Threading;
using System.Collections;

namespace sync_root_2 {

// User defined class X
class X {

    int x;

    // defining Constructor
    public X()
    {
        x = 0;
    }

    // Method to get the value
    // stored in x
    public int getValue()
    {
        return x;
    }
}

// Driver Class
public class Program {

    // Main Method
    static void Main(string[] args)
    {
        // Declaring an array of objects
        // of type class X
        X[] obj = new X[5];

        // Calling the constructor
        // for each object
        for (int i = 0; i < 5; i++)
            obj[i] = new X();

        // Synchronizing the array
        lock(obj.SyncRoot)
        {
            // Displaying the value
            foreach(X element in obj)
                Console.WriteLine(element.getValue());
        }
    }
}
}
Reference:

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4