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.
- Download AsyncMVVM-Silverlight-VB.zip [2mb, requires VS2012]
- Download AsyncMVVM-Silverlight-CS.zip [2mb, requires VS2012]
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
Comments
Anonymous
June 20, 2013
I have no idea which visual studio to open this with...Anonymous
June 30, 2013
Sry I got a little bit grumpy before; I am just trying Silverlight for the first time, in order to understand this example. After I managed to get the c# version to build (including generating the xap file) i tried deploying it, and got a security error when I press Fetch: System.Security.SecurityException ---> System.Security.SecurityException: Security error. as System.Net.Browers.BrowerHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult) .. On finding out more about silverlight, apparently it needs a special xml file on the target for a request. I looked in fiddler to see what the app was requesting, and it was requesting /clientaccesspolicy.xml and /crossdomain.xml on the server, and both requests got a 404 response. So, that's my foray into silverlight, maybe I am missing something.