title: MVVM async await pattern
body: <p>I've been trying to write an MVVM screen for a WPF application, using the async &amp; await keywords to write asynchronous methods for 1. Initially loading data, 2. Refreshing the data, 3. Saving changes and then refreshing. Although I have this working, the code is very messy and I can't help thinking that there must be a better implementation. Can anyone advise on a simpler implementation?</p>
  
  <p>This is a cut-down version of my ViewModel:</p>
  
  <pre><code>public class ScenariosViewModel : BindableBase
  {
      public ScenariosViewModel()
      {
          SaveCommand = new DelegateCommand(async () =&gt; await SaveAsync());
          RefreshCommand = new DelegateCommand(async () =&gt; await LoadDataAsync());
      }
  
      public async Task LoadDataAsync()
      {
          IsLoading = true; //synchronously set the busy indicator flag
          await Task.Run(() =&gt; Scenarios = _service.AllScenarios())
              .ContinueWith(t =&gt;
              {
                  IsLoading = false;
                  if (t.Exception != null)
                  {
                      throw t.Exception; //Allow exception to be caught on Application_UnhandledException
                  }
              });
      }
  
      public ICommand SaveCommand { get; set; }
      private async Task SaveAsync()
      {
          IsLoading = true; //synchronously set the busy indicator flag
          await Task.Run(() =&gt;
          {
              _service.Save(_selectedScenario);
              LoadDataAsync(); // here we get compiler warnings because not called with await
          }).ContinueWith(t =&gt;
          {
              if (t.Exception != null)
              {
                  throw t.Exception;
              }
          });
      }
  }
  </code></pre>
  
  <p>IsLoading is exposed to the view where it is bound to a busy indicator.</p>
  
  <p>LoadDataAsync is called by the navigation framework when the screen is first viewed, or when a refresh button is pressed. This method should synchronously set IsLoading, then return control to the UI thread until the service has returned the data. Finally throwing any exceptions so they can be caught by the global exception handler (not up for discussion!).</p>
  
  <p>SaveAync is called by a button, passing updated values from a form to the service. It should synchronously set IsLoading, asynchronously call the Save method on the service and then trigger a refresh.</p>