A pattern for Silverlight’s asynchronous operations

Silverlight can only invoke web operations asynchronously. Normally this would have led to a mess of logic. However, with anonymous methods, the problem can be managed. People who are familiar to Ruby blocks would see the similarity.

In the VB.net example below, I have a function AllocateSerialNumber which (eventually) returns a string.


Imports  System.ServiceModel.DomainServices.Client

Dim myDomainContext As New Web.MyDomainContext

' This code does a lot
' AllocateSerialNumber() calls the function
' AddHandler ... Sub waits until the operation has completed
' The Sub routine uses the webResponse.Value
'
AddHandler myDomainContext.AllocateSerialNumber(1, 2).Completed, _
    Sub(webResponse As InvokeOperation, e2 As EventArgs)
        If Not webResponse.HasError Then
            MessageBox.Show(webResponse.Value)
        Else
            ' Your error handling here
            MessageBox.Show(webResponse.Error.Message)
            operation.MarkErrorAsHandled()
        End If
    End Sub

a more verbose option follows

Dim myDomainContext As New Web.MyDomainContext

' This code does a lot
' AllocateSerialNumber() calls the function
' AddHandler ... Sub waits until the operation has completed
' The Sub routine consumes the result
'
AddHandler myDomainContext.AllocateSerialNumber(1, 2).Completed, _
    Sub(sender2 As Object, e2 As EventArgs)
        Dim webResponse As System.ServiceModel.DomainServices.Client.InvokeOperation _
            = CType(sender2, System.ServiceModel.DomainServices.Client.InvokeOperation)
        If Not webResponse.HasError Then
            MessageBox.Show(webResponse.Value)
        Else
            ' Your error handling here
            MessageBox.Show(webResponse.Error.Message)
            operation.MarkErrorAsHandled()
        End If
    End Sub

About this entry