DTSReadOnlyCollectionBase.SyncRoot Property

Definition

获取用于同步对 DTSReadOnlyCollectionBase 的访问的对象。Gets an object that can be used to synchronize access to the DTSReadOnlyCollectionBase.

public:
 property System::Object ^ SyncRoot { System::Object ^ get(); };
public object SyncRoot { get; }
member this.SyncRoot : obj
Public ReadOnly Property SyncRoot As Object

Property Value

Object

用于同步对 DTSReadOnlyCollectionBase 的访问的对象。An object that can be used to synchronize access to the DTSReadOnlyCollectionBase.

Implements

Examples

下面的代码示例演示如何 ArrayList 在枚举期间使用锁定集合 SyncRootThe following code example shows how to lock an ArrayList collection using the SyncRoot during the enumeration.

using System;  
using System.Collections;  
  
ArrayList myCollection = new ArrayList();  
lock( myCollection.SyncRoot )   
foreach ( Object item in myCollection )   
{  
    // Insert your code here.  
}  
Imports System  
Imports System.Collections  
  
Dim myCollection As ArrayList =  New ArrayList()   
  
lock(myCollection.SyncRoot)  
For Each item In myCollection  
    ' Insert your code here.  
Next  

Remarks

实现system.collections.icollection.issynchronizedImplements ICollection.IsSynchronized. 如果要创建自定义集合并从派生 DTSReadOnlyCollectionBase ,则可以使用属性提供自己的同步版本集合 SyncRootIf you are creating a custom collection and deriving from DTSReadOnlyCollectionBase, you can provide your own synchronized version of the collection 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 object.

枚举整个集合本质上不是一个线程安全的过程。Enumerating through a collection is intrinsically not a thread-safe procedure. 即使集合是同步的,其他线程仍可以修改集合,这会导致枚举器引发异常。Even when a collection is synchronized, other threads could 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. 有关详细信息,请参阅system.collections.icollection.issynchronizedFor more information, see ICollection.IsSynchronized.

Applies to