'宣言 Public Overridable ReadOnly Property ThreadSynchronizationCollection As IEnumerable
public virtual IEnumerable ThreadSynchronizationCollection {get;}
.NET Framework 4.5 で Microsoft がクロス スレッドの更新のサポートおよび BindingOperations の EnableCollectionSynchronization および AccessCollection メソッドによってアクセスするサポートを追加しました。このシナリオで、AllValues プロパティを安全に繰り返すために ThreadSynchronizationCollection プロパティを使用できます。例:
BindingOperations.AccessCollection(context.ThreadSynchronizationCollection, new Action(() =>
{
foreach (ValueEntry ii in context.AllValues)
{
/// ... process the entry
}
}), false);
注: その AccessCollection メソッドを呼び出す各スレッドは .NET Framework 4.5 で追加された BindingOperations.EnableCollectionSynchronization を呼び出す必要があります。特定のコレクションで各スレッドに同じロック オブジェクトと呼び出す必要があります。例:
var list = new ObservableCollection<MyClass>();
var lockingObj = new object();
// Call EnableCollectionSynchronization on the UI thread
BindingOperations.EnableCollectionSynchronization(list, lockingObj);
// Note: that XamDataGrid will only support cross-thread updating if the list is in a CollectionView
XamDataGrid1.DataSource = CollectionViewSource.GetDefaultView(list);
// perform updating of the collection on a background thread using locks
Task.Run(new Action(() =>
{
// lock using the same locking object that was passed into EnableCollectionSynchronization
// above on the UI thread
lock(lockingObj)
{
list.Add(new MyClass());
}
}));
// Alternatively, you can perform updating of the collection on a background thread using AccessCollection, e.g.:
Task.Run(new Action(() =>
{
// Since we will be calling AccessCollection on this thread we need to first call
// EnableCollectionSynchronization with the same locking object
BindingOperations.EnableCollectionSynchronization(list, lockingObj);
// calling AccessCollection will wrap the action in a synchronization lock
BindingOperations.AccessCollection(list, new Action(() =>
{
list.Add(new MyClass());
}), true);
}));