MVVM: Asynchronous Commands

Posted on | 251 words | ~2 mins
C# WPF MVVM

The latest cut of the Apex Code (http://apex.codeplex.com/SourceControl/changeset/changes/6701) contains a very cool new feature - Asynchronous Command Objects.

An Asynchronous Command is a ViewModelCommand - the standard object used in Apex for commanding. However, what is different about this function is that it runs Asynchronously.

One of the problems with running a view model command asynchronously is that generally the view model properties cannot be accessed - as they're created on a different dispatcher. This problem is resolved by using the 'ReportProgress' function. Here's an example:

public class SomeViewModel : ViewModel
{
  public SomeViewModel()
  {
     // Create the command.
     asyncCommand = new AsynchronousCommand(DoAsyncCommand, true);
  }

private void DoAsyncCommand() { for(int i = 0; i < 100; i++) { // Perform some long operation. string message = DoSomeLongOperation();

    // Add the message to the View Model - safely!
    asyncCommand.ReportProgress(
      () =&gt;
      {
         messages.Add(message);
      }
    );
 }

}

private ObservableCollection<string> messages = new ObservableCollection<string>();

public ObservableCollection<string> Messages { get { return messages; } }

private AsynchronousCommand asyncCommand;

public AsynchronousCommand AsyncCommand { get { return asyncCommand; } } }

In this basic mock-up we have a command called 'AsyncCommand' (which we could bind a button to for example) which invokes DoAsyncCommand. However, it invokes it Asynchronously. We can also update the ViewModel properties by using ReportProgress - meaning AsyncCommands can seamlessly provide live feedback while they're working - and we're keeping well locked in with the MVVM commanding model!

Expect a full article soon on the CodeProject, until then the source is at:

http://apex.codeplex.com/SourceControl/changeset/changes/6701