在单独的线程上时,视图未更新 [英] View is not updated when on a separate thread

查看:102
本文介绍了在单独的线程上时,视图未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在单独的线程中加载一些数据,然后将加载的数据添加到ObservableCollection并通过ba绑定更新视图.

I am trying to load some data in a separate thread, then add the loaded data to an ObservableCollection and update the view through ba binding.

首先,我正在执行以下操作:

First, I was doing the following:

public OverviewViewModel()
{
    Thread thread = new Thread(new ThreadStart(delegate
    {
        TheTVDB theTvdb = new TheTVDB();
        foreach (TVSeries tvSeries in theTvdb.SearchSeries("Dexter"))
        {
            this.Overview.Add(tvSeries);
        }
    }));
    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
}

这给出了以下错误:

这种类型的CollectionView不支持对其更改的更改 来自与Dispatcher线程不同的线程的SourceCollection.

This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread.

所以我在这个论坛上读到我应该使用Dispatcher,因此我将this.Overview.Add(tvSeries)放入对Dispatcher的呼叫中.

So I read on this forum that I should use the Dispatcher, so I put this.Overview.Add(tvSeries) into a call to the Dispatcher.

Dispatcher.CurrentDispatcher.BeginInvoke((Action)delegate
{
    this.Overview.Add(tvSeries);
},
DispatcherPriority.Normal);

现在,它不再崩溃,但视图未更新.没有任何反应,该视图只是空的.我已经通过在主线程上运行它来测试了该功能.然后,视图将正确更新.

Now, it doesn't crash anymore but the view is not updated. Nothing happens, the view is just empty. I have tested the functionality by running it on the main thread. Then the view is updated correctly.

有人知道为什么视图未更新以及我该如何解决吗?

Does anyone know why the view is not updated and how I can fix this?

更新

以下方法似乎可行,并且似乎可以异步完成所有操作.谁能确认这是异步做事的正确方法?

The below approach seems to work and it seems to do everything asynchronously. Can anyone confirm that this is the right approach for doing things asyncronously?

Dispatcher.CurrentDispatcher.BeginInvoke(new Action(delegate
{
    TheTVDB theTvdb = new TheTVDB();
    foreach (TVSeries tvSeries in theTvdb.SearchSeries("Dexter"))
    {
        this.Overview.Add(tvSeries);
    }
}),
DispatcherPriority.Background);

推荐答案

这是因为您需要告诉WPF Dispatcher处理线程活动.

This is because you will need to tell WPF Dispatcher to handle the threading activity.

查看本文以获取更多核心详细信息,并且示例

Check this article for more of the core details, and this one for some additional examples.

阅读内容可能有点繁琐,但是如果您使用的是WPF,则值得学习Dispatcher的工作原理.

The reading can be a bit heavy, but if you're working with WPF, it's well worth learning about how the Dispatcher works.

第二篇文章实际上明确提到了您的问题.

The second article actually explicitly mentions your problem.

最后,请不要忘记ObservableCollection将仅触发INPC事件以执行添加/删除操作,而不触发单个元素更改.为此,您需要在基础项目本身上实现INPC.

Lastly, don't forget that ObservableCollection will only fire INPC events for add / remove actions, and not individual element changes. For that you'll need to implement INPC on the underlying items themselves.

这篇关于在单独的线程上时,视图未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆