多线程下异常:某个ItemsControl与它的项源不一致


         这两天写一个WPF的客户端,为DataGrid绑定了一个List的集合作为数据源(没用ObservableCollection,想在另一个地方进行refresh操作),但是就这么简单一个玩意,写完后执行却发生bug,bug页面如下:


        通过Google,找到问题和解决方案。问题就是多线程的环境下,对数据源集合的更新操作会和UI线程的显示产生冲突。如何解决?看下面


void UpdateItems()
{
    //retrievedItems is the data you received from the service
    foreach(object item in retrievedItems)
        Dispatcher.BeginInvoke(DispatcherPriority.Background, new ParameterizedThreadStart(AddItem), item);    
}

void AddItem(object item)
{
    observableCollection.Add(item);
}

还是把数据源改成ObservableCollection,再用这个异步更新,好了,bug搞定了。

源链接在此:http://stackoverflow.com/questions/2505492/wpf-update-binding-in-a-background-thread

       

        最后感叹一句,中文的资源真是少啊,Google问题还是要用英文,上面这个问题用下面这句进行搜索

An ItemsControl is inconsistent with its items source,就能在stackoverflow上搜到一堆解决方案。































                                                                                                               

posted @ 2019-12-15 09:26  夜读春秋  阅读(684)  评论(0编辑  收藏  举报