I hit my head on the virtual wall for several days. The BindingOperations.EnableSynchronization method only works partially in .NET 4.5.
I wrote a test that sometimes fails:
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 is as follows:
<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>
Nothing magical here. But the result is almost every time that some entries twice in the user interface are the same objects! The results window looks like this:
Sandra Bullock 1
Jennifer Aniston 2
Jennifer Lopez 3
Angelina Jolie 4
Mary Elizabeth Mastrantonio 5
Jennifer Aniston 2
As you can clearly see, Jennifer Aniston is listed twice. It can be easily reproduced. Is this a common problem or is there something wrong with this test, for example, incorrect application implementation?
Thank you in advance!
Jens Mig May 12 '13 at 20:17 2013-05-12 20:17
source share