MVVM with Async - sample code

How do you combine MVVM with async? -- Well, really, there's not much to it. Just the same as always. Here's an example Silverlight MVVM project. It first shipped with the Async CTP, and I've updated it to use VS2012 and Microsoft.Bcl.Async.

One thing that makes it easier with async/await is that these keywords don't introduce new threads. This makes things a lot easier. It means that all your work can be done on the  UI thread: even when you update databound properties, or add elements to a databound observable collection, it's all on the UI thread and so works fine.

 

I just want to call out ICommand.Execute. We all know that async voids should only be used for top-level event-handlers, or event-like things. Well, ICommand.Execute is an top-level event-like thing, so it's okay for it to be async void. Just remember that all exceptions that come out of an async void will be posted straight to the UI thread.

 

Public Class FetchCommand

    Implements ICommand

    Friend vm As MainPageViewModel

 

    Friend Sub Invalidate()

        RaiseEvent CanExecuteChanged(Me, EventArgs.Empty)

    End Sub

 

    Public Function CanExecute(p As Object) As Boolean Implements ICommand.CanExecute

        Return Not vm.Fetching

    End Function

 

    Public Event CanExecuteChanged(s As Object, e As EventArgs) Implements ICommand.CanExecuteChanged

 

    Public Sub Execute(parameter As Object) Implements ICommand.Execute

        vm.DoFetch() ' DoFetch is an Async Sub (i.e. void-returning async)

    End Sub

 

End Class