📜  如何在C#中获得对数组的同步访问

📅  最后修改于: 2021-05-30 01:26:27             🧑  作者: Mango

Array.SyncRoot属性用于获取一个对象,该对象可用于同步对Array的访问。数组是一组由通用名称引用的相似类型的变量。数组类位于System命名空间下。

重要事项:

  • 完成对象的同步,以便只有一个线程可以操纵数组中的数据。
  • 属性是提供读取,写入和计算私有数据字段的手段的类的成员。
  • Array.SyncRoot属性实现System.Collections.ICollection接口。
  • 同步代码不能直接在集合上执行,因此它必须在集合的SyncRoot上执行操作,以保证从其他对象派生的集合的正确操作。
  • 检索此属性的值是O(1)操作。

示例1:在此代码中,我们使用SyncRoot获取对名为arr的Array的同步访问,这不是线程安全的过程,并且可能导致异常。因此,为避免异常,我们在枚举期间锁定了集合。

// 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);
        }
    }
}
}
输出:
12
15
20
3
6

示例2:在下面的示例中,我们将SynRoot属性与X类的对象一起使用。

// 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());
        }
    }
}
}
输出:
0
0
0
0
0

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.array.syncroot?view=netframework-4.7.2