Array.IsSynchronized 属性

定义

获取一个值,该值指示是否同步对 Array 的访问(线程安全)。Gets a value indicating whether access to the Array is synchronized (thread safe).

public:
 property bool IsSynchronized { bool get(); };
public:
 virtual property bool IsSynchronized { bool get(); };
public bool IsSynchronized { get; }
public virtual bool IsSynchronized { get; }
member this.IsSynchronized : bool
Public ReadOnly Property IsSynchronized As Boolean
Public Overridable ReadOnly Property IsSynchronized As Boolean

属性值

Boolean

对于所有数组,此属性始终为 falseThis property is always false for all arrays.

实现

示例

下面的代码示例演示如何使用属性在整个枚举过程中锁定数组 SyncRootThe following code example shows how to lock an array during the entire enumeration by using the SyncRoot property.

Array^ myArray = gcnew array<Int32> { 1, 2, 4 };
try
{
    Monitor::Enter(myArray->SyncRoot); 
        
    for each (Int32 item in myArray)
        Console::WriteLine(item);
}
finally
{
    Monitor::Exit(myArray->SyncRoot);
}
Array myArray = new int[] { 1, 2, 4 };
lock(myArray.SyncRoot)
{
    foreach (Object item in myArray)
        Console.WriteLine(item);
}
Dim myArray As Array = New Integer() { 1, 2, 4 }
SyncLock(myArray.SyncRoot) 
    For Each item As Object In myArray
        Console.WriteLine(item)
    Next
End SyncLock

注解

Array 实现 IsSynchronized 属性,因为它是接口所必需的 System.Collections.ICollectionArray implements the IsSynchronized property because it is required by the System.Collections.ICollection interface.

基于的 .NET 类 Array 使用属性提供自己的集合的同步版本 SyncRoot.NET classes based on Array provide their own synchronized version of the collection using the SyncRoot property.

使用数组的类也可以使用属性来实现自己的同步 SyncRootClasses that use arrays can also implement their own synchronization using the SyncRoot property. 同步代码必须对 SyncRoot 集合的(而不是直接在集合上)执行操作。The synchronizing code must perform operations on the SyncRoot of the collection, not directly on the collection. 这样可确保对从其他对象派生的集合正确地执行操作。This ensures proper operation of collections that are derived from other objects. 具体而言,它与可能同时修改集合的其他线程保持正确的同步。Specifically, it maintains proper synchronization with other threads that might be simultaneously modifying the collection. 请注意,的某些实现 SyncRoot 可能会返回 Array 自身。Note that some implementations of SyncRoot might return the Array itself.

枚举集合本质上不是线程安全的过程。Enumerating through a collection is intrinsically not a thread safe procedure. 即使某个集合已同步,其他线程仍可以修改该集合,这会导致枚举数引发异常。Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. 若要确保枚举过程中的线程安全性,可以在整个枚举期间锁定集合,或者捕获由其他线程进行的更改所导致的异常。To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

检索此属性的值的运算复杂度为 O(1)。Retrieving the value of this property is an O(1) operation.

适用于

另请参阅