3

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?

Real World
  • 1,593
  • 1
  • 21
  • 46

2 Answers2

4

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.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • if it is code that is run logically/once when called, i.e not needing a timer that schedules.. is there a simpler way to avoid dispatcher and the window.current == null problem? – Allstar Aug 14 '19 at 08:34
  • @Allstar: I'm not clear on the requirements. Could you post your own question along with code? – Stephen Cleary Aug 14 '19 at 12:25
  • @StephenCleary , here it is: https://stackoverflow.com/questions/57522322/correct-way-to-access-ui-from-background-thread-in-uwp Thank you. – Allstar Aug 16 '19 at 09:40
0

Try using

Deployment.Current.Dispatcher.BeginInvoke

or

Application.Current.Dispatcher.BeginInvoke
Alberto
  • 15,626
  • 9
  • 43
  • 56