Must create DependencySource on same Thread as DependencyObject

后端 未结 3 1050
甜味超标
甜味超标 2021-01-04 14:10

I have an application written in wpf, which downloads some webpages, parses html code and saves some values.

class ListOfItems
{    
    public List

        
相关标签:
3条回答
  • 2021-01-04 14:29

    The SolidColorBrush is a Freezable which is a derived DispatcherObject. DispatcherObjects have thread affinity - i.e it can only be used/interacted with on the thread on which it was created. Freezables however do offer the ability to freeze an instance. This will prevent any further changes to the object but it will also release the thread affinity. So you can either change it so that your property is not storing a DependencyObject like SolidColorBrush and instead just store the Color. Or you can freeze the SolidColorBrush that you are creating using the Freeze method.

    0 讨论(0)
  • 2021-01-04 14:38

    I think the standard way is to derive the data object from Freezable and Freeze it before passing it to another thread. Once the object is frozen, you can't change it any more, so there's no danger of threading bugs.

    Another option might be to make the data object a plain C# object (not derived from DispatcherObject) and implement INotifyPropertyChanged yourself.

    0 讨论(0)
  • 2021-01-04 14:39

    Its not enough to set your dataGrid.ItemsSource on the main thread. You must create each item on the main-thread. Something like:

    List<SomeObject> l = new List<SomeObject>();
    foreach(var item in ListOfItemsInstance.ListToBind)
    {
        l.Add(new SomeObject(){NameOfItem = item.NameOfItem, Properties = item.Properties });
    }
    
    dataGrid.ItemsSource = l;
    
    0 讨论(0)
提交回复
热议问题