从非UI线程更新ObservableCollection [英] Updating ObservableCollection from non UI thread

查看:105
本文介绍了从非UI线程更新ObservableCollection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Windows 8 Store应用程序.我有一个计时器,每两分钟调用一次代理,并发出一个异步Web请求.结果数据将添加到绑定到UI元素的observablecollection中.这样做会引发异常,因为正在非UI线程上修改UI. 在我的代码的其他地方,我已经做到了

I am working on a Windows 8 Store app. I have a timer that calls a delegate every two minutes and makes an async web request. The resulting data is added to an observablecollection that is bound to a UI element. Doing this throws an exception because the UI is being modified on a non UI thread. In other places in my code I have done this

await Window.Current.CoreWindow.Dispatcher.RunAsync( CoreDispatcherPriority.Normal, async () =>
{
    ui code here
}

但这会导致Window.Current为null的崩溃.我尝试将Window.Current作为参数传递给委托,但这会引发不同的异常.关于如何解决这个问题有什么建议吗?

But this is causing a crash with Window.Current being null. I tried passing Window.Current into the delegate as a parameter but this throws a different exception. Are there any suggestions on how to solve this?

推荐答案

让UI线程调用后台操作通常比让后台操作更新UI线程更容易.

It's usually easier to have the UI thread call background operations rather than having the background operations update the UI thread.

因此,我建议您使用 ,那么您完全不需要使用Dispatcher.

So, I recommend you use DispatcherTimer, and then you won't need to use Dispatcher at all.

这篇关于从非UI线程更新ObservableCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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