2

How to call an async method into a method that implements an interface when this method is NOT async?

In my ViewModel, I've got an async method that should be executed each time the user navigates into the view.

The fastest (bad) solution I was able to find is this one

public class MyViewModel : INavigationAware
{
    //[...]
    public async void OnNavigatedTo(NavigationContext navigationContext)
    {
        await Refresh();
    }
    public async Task Refresh()
    {
        await Task.Run(() => 
        {
           // Asynchronous work
        });
        /* Actions on Gui Thread */           
    }
    //[...]
}
JiBéDoublevé
  • 4,124
  • 4
  • 36
  • 57

1 Answers1

1

This should work for this, based on what I can gather from the question. I did a quick test with a project I am working on to see the concept work. The Refresh method should run each time you navigate to the view using this view model.

public class MyViewModel : INavigationAware
{
    //[...]
    public void OnNavigatedTo(NavigationContext navigationContext)
    {
        Refresh();
    }
    public async void Refresh()
    {
        await Task.Run(() => 
        {
           // Asynchronous work
        }).ContinueWith(t=> /* Actions on Gui Thread */, TaskScheduler.FromCurrentSynchronizationContext());            
    }
    //[...]
}

I removed the async/await on the OnNavigatedTo, and had that call an async Refresh method that returns nothing.

R. Richards
  • 24,603
  • 10
  • 64
  • 64