问题
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