Search code examples
c#microsoft-metrowinrt-async

Metro app, don't freeze UI


I'm writing a metro application with a lot of call to webservice. Sometimes the web service is a bit slow. And I don't want to wait within a page until my data are downloaded.

But, my back button is disabled until my data have been loaded. Which is a big problem.

So I tried with :

 try
{
    await Task.Run(() =>
                       {
                           Dispatcher.RunAsync(CoreDispatcherPriority.High, 
                           () => ViewModel.InitAsync(date)).AsTask(_cts.Token);
                       }, _cts.Token);
}catch(Exception e)
{
    Debug.WriteLine("HomePage, LoadState : "+e);
}

Note;

I use Task.Run to be able to use a cancellationtoken. And Dispatcher.RunAsync should allow me to not freeze my UI. This is used within page LoadState.

How could I fix this issue ?

Regards.

Updated with (doesn't fix my issue):

try
{
    Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    ViewModel.InitAsync(date)).AsTask(_cts.Token);
}catch(Exception e)
{
    Debug.WriteLine("HomePage, LoadState : "+e);
}

Solution

  • You can't just throw Task.Run and Dispatcher.RunAsync at your problems. You need to understand what they do.

    In your case, you should be able to just do this:

    try
    {
      await ViewModel.InitAsync(date);
    }
    catch (Exception e)
    {
      Debug.WriteLine("HomePage, LoadState : " + e);
    }