user3305007
user3305007

Reputation: 41

How to use the Dispatcher to run code on UI from within a resuming event handler in a windows store app

I am developing a Windows store app library and I want to execute code on UI Thread when the application is resuming from suspending state.

Here is an example of my code:

  /* Set the on resuming handler. */
  Application.Current.Resuming += (s, e) =>
  {
    Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
    () =>
    {
      /* Do something on UI thread. */
    });
  };

The problem is that the RunAsync hangs before it had times to execute any code on the UI thread. In fact, the application hangs on any call to CoreApplication.MainView.

So, what could I do to execute code on UI thread when the App is resuming from suspending state?

Upvotes: 1

Views: 1481

Answers (3)

Kushal Maniyar
Kushal Maniyar

Reputation: 876

 await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    (Windows.UI.Xaml.Window.Current.Content as Windows.UI.Xaml.Controls.Frame).Navigate(typeof(SamplePage));
                });

Upvotes: 0

user3305007
user3305007

Reputation: 41

Thanks for the advise Nate. But here is a simple solution :

  /* Set the new handler. */
  Application.Current.Resuming += (s, e) =>
  {
    /* Start a task to wait for UI. */
    Task.Factory.StartNew(() =>
    {
      Windows.Foundation.IAsyncAction ThreadPoolWorkItem = Windows.System.Threading.ThreadPool.RunAsync(
      (source) =>
      {
        Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
         () =>
         {
           /* Do something on UI thread. */
         });
      });
    });
  };

This may not be the perfect solution but it works.

Upvotes: 1

Nate Diamond
Nate Diamond

Reputation: 5575

I believe that the Dispatcher is likely null at that point. What you should do is wait to do the UI-centric processing until the page that you are navigating to is loading. This may mean that you should navigate to a loading page before going to the page that you are resuming.

Upvotes: 0

Related Questions