Why does CollectionViewSource.GetDefaultView(…) return the wrong CurrentItem from inside a Task thread?

后端 未结 1 851
我寻月下人不归
我寻月下人不归 2021-01-22 14:55

I have what I think is a fairly standard setup, a ListBox backed by an ObservableCollection.

I have some work to do with the Thing

1条回答
  •  梦毁少年i
    2021-01-22 15:37

    I believe CollectionViewSource.GetDefaultView is effectively thread-static - in other words, each thread will see a different view. Here's a short test to show that:

    using System;
    using System.Windows.Data;
    using System.Threading.Tasks;
    
    internal class Test
    {
        static void Main() 
        {
            var source = "test";
            var view1 = CollectionViewSource.GetDefaultView(source);
            var view2 = CollectionViewSource.GetDefaultView(source);        
            var view3 = Task.Factory.StartNew
                (() => CollectionViewSource.GetDefaultView(source))
                .Result;
    
            Console.WriteLine(ReferenceEquals(view1, view2)); // True
            Console.WriteLine(ReferenceEquals(view1, view3)); // False
        }        
    }
    

    If you want your task to work on a particular item, I suggest you fetch that item before starting the task.

    0 讨论(0)
提交回复
热议问题