Updating ObservableCollection from non UI thread

时光总嘲笑我的痴心妄想 提交于 2020-01-24 15:42:06

问题


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
}

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?


回答1:


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

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




回答2:


Try using

Deployment.Current.Dispatcher.BeginInvoke

or

Application.Current.Dispatcher.BeginInvoke


来源:https://stackoverflow.com/questions/18872112/updating-observablecollection-from-non-ui-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!