Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating ObservableCollection from non UI thread

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?

like image 934
Real World Avatar asked Feb 15 '26 08:02

Real World


1 Answers

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.

like image 144
Stephen Cleary Avatar answered Feb 17 '26 21:02

Stephen Cleary