ControlCollection.SyncRoot 屬性
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
取得可用來對控制項集合進行同步 (Synchronize) 存取的物件。
public:
property System::Object ^ SyncRoot { System::Object ^ get(); };
public object SyncRoot { get; }
member this.SyncRoot : obj
Public ReadOnly Property SyncRoot As Object
屬性值
用來同步處理集合的 Object。
實作
範例
下列程式碼範例會建立方法,以列舉 ControlCollection 控制項 myButton
的 Button 集合。 建立列舉值時, IsSynchronized 會檢查 屬性,以查看作業是否為安全線程,如果不是,則會 SyncRoot 使用 屬性來取得物件,讓作業執行緒安全。 當列舉完成時,屬性的值 IsReadOnly 會寫入為 Text 包含頁面上控制項的 Label 屬性。
// Create a method that enuberates through a
// button//s ControlCollection in a thread-safe manner.
public void ListControlCollection(object sender, EventArgs e)
{
IEnumerator myEnumerator = myButton.Controls.GetEnumerator();
// Check the IsSynchronized property. If False,
// use the SyncRoot method to get an object that
// allows the enumeration of all controls to be
// thread safe.
if (myButton.Controls.IsSynchronized == false)
{
lock (myButton.Controls.SyncRoot)
{
while (myEnumerator.MoveNext())
{
Object myObject = myEnumerator.Current;
LiteralControl childControl = (LiteralControl)myEnumerator.Current;
Response.Write("<b><br /> This is the text of the child Control </b>: " +
childControl.Text);
}
msgReadOnly.Text = myButton.Controls.IsReadOnly.ToString();
}
}
}
' Create a method that enuberates through a
' button's ControlCollection in a thread-safe manner.
Public Sub ListControlCollection(sender As Object, e As EventArgs)
Dim myEnumerator As IEnumerator = myButton.Controls.GetEnumerator()
' Check the IsSynchronized property. If False,
' use the SyncRoot method to get an object that
' allows the enumeration of all controls to be
' thread safe.
If myButton.Controls.IsSynchronized = False Then
SyncLock myButton.Controls.SyncRoot
While (myEnumerator.MoveNext())
Dim myObject As Object = myEnumerator.Current
Dim childControl As LiteralControl = CType(myEnumerator.Current, LiteralControl)
Response.Write("<b><br /> This is the text of the child Control </b>: " & _
childControl.Text)
End While
msgReadOnly.Text = myButton.Controls.IsReadOnly.ToString()
End SyncLock
End If
End Sub