几天来,我一直在用头撞虚拟墙。BindingOperations.EnableSynchronization 方法似乎只在 .NET 4.5 中部分起作用。
我写了一个有时会失败的测试:
object blah = new object();
Application app = Application.Current == null ? new Application() : Application.Current;
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
ObservableCollection<ThreadSafeObservableTestObject> collection = null;
collection = new ObservableCollection<ThreadSafeObservableTestObject>();
BindingOperations.EnableCollectionSynchronization(collection, blah);
CollectionTestWindow w = new CollectionTestWindow();
Task.Factory.StartNew(() =>
{
Thread.Sleep(2000);
w.TestCollection = collection;
collection.CollectionChanged += collection_CollectionChanged;
collection.Add(new ThreadSafeObservableTestObject() { ID = 1, Name = "Sandra Bullock" });
collection.Add(new ThreadSafeObservableTestObject() { ID = 2, Name = "Jennifer Aniston" });
collection.Add(new ThreadSafeObservableTestObject() { ID = 3, Name = "Jennifer Lopez" });
collection.Add(new ThreadSafeObservableTestObject() { ID = 4, Name = "Angelina Jolie" });
collection.Add(new ThreadSafeObservableTestObject() { ID = 5, Name = "Mary Elizabeth Mastrantonio" });
Thread.Sleep(5000);
System.Windows.Application.Current.Dispatcher.Invoke(() => w.Close());
System.Windows.Application.Current.Dispatcher.Invoke(() => Application.Current.Shutdown());
});
app.Run(w);
TestCollectionWindow 如下所示:
<ItemsControl ItemsSource="{Binding TestCollection}" Name="list">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" />
<TextBlock Text="{Binding ID}" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
所以这里没有什么神奇的。但结果几乎每次某些条目在 UI 中出现两次 - 相同的对象!结果窗口如下所示:
桑德拉·布洛克 1
詹妮弗·安妮斯顿 2
詹妮弗·洛佩兹 3
安吉丽娜·朱莉 4
玛丽·伊丽莎白·马斯特兰托尼奥 5
詹妮弗·安妮斯顿 2
正如你可以清楚地看到詹妮弗安妮斯顿被列出两次。这可以很容易地复制。这是一个普遍的问题还是这个测试有什么问题,例如有缺陷的应用程序实例化?
先感谢您!