ArrayList.IsSynchronized 属性

定义

获取一个值,该值指示是否同步对 ArrayList 的访问(线程安全)。

C#
public virtual bool IsSynchronized { get; }

属性值

如果对 true 的访问是同步的(线程安全),则为 ArrayList;否则为 false。 默认值为 false

实现

示例

下面的代码示例演示如何在整个枚举期间使用 SyncRoot 锁定集合。

C#
ArrayList myCollection = new ArrayList();

lock(myCollection.SyncRoot)
{
    foreach (object item in myCollection)
    {
        // Insert your code here.
    }
}

检索此属性的值是一项 O(1) 操作。

下面的代码示例演示如何同步 , ArrayList确定 是否 ArrayList 同步并使用同步的 ArrayList

C#
using System;
using System.Collections;
public class SamplesArrayList  {

   public static void Main()  {

      // Creates and initializes a new ArrayList.
      ArrayList myAL = new ArrayList();
      myAL.Add( "The" );
      myAL.Add( "quick" );
      myAL.Add( "brown" );
      myAL.Add( "fox" );

      // Creates a synchronized wrapper around the ArrayList.
      ArrayList mySyncdAL = ArrayList.Synchronized( myAL );

      // Displays the sychronization status of both ArrayLists.
      Console.WriteLine( "myAL is {0}.", myAL.IsSynchronized ? "synchronized" : "not synchronized" );
      Console.WriteLine( "mySyncdAL is {0}.", mySyncdAL.IsSynchronized ? "synchronized" : "not synchronized" );
   }
}
/*
This code produces the following output.

myAL is not synchronized.
mySyncdAL is synchronized.
*/

注解

若要保证 的 ArrayList线程安全,所有操作都必须通过 方法返回的 Synchronized 包装器来完成。

枚举整个集合本质上不是一个线程安全的过程。 即使某个集合已同步,其他线程仍可以修改该集合,这会导致枚举数引发异常。 若要确保枚举过程中的线程安全性,可以在整个枚举期间锁定集合,或者捕获由其他线程进行的更改所导致的异常。

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1
UWP 10.0

另请参阅