Do you want to buy me a beer or coffee?

Wednesday, December 9, 2009

Three Options for Making Asynchronous Calls

Three Options for Making Asynchronous Calls

Every application is different, and there are scenarios for making asynchronous calls that work for some applications that may not work for others. The .NET Framework is quite flexible in the ways that it provides for making asynchronous calls. You can either poll to see when a request completes, block on the WaitHandle, or wait for the callback function. Let's take a look at each of these approaches.

' Polling code that could tie up your processor

Dim proxy as New localhost.Service1()
Dim result as IAsyncResult Result = proxy.BeginDelayedResponse(2000, _ Nothing, _ Nothing)
While (result.IsCompleted = False)
' Do some processing ...
Wend
Dim response as String response = proxy.EndDelayedResponse(result)


' Simple WaitHandle code
Dim proxy As New localhost.Service1()
Dim result As IAsyncResult
result = proxy.BeginDelayedResponse(2000, Nothing, Nothing)
' Do some processing.
' ...
' Done processing. Wait for completion.
result.AsyncWaitHandle.WaitOne()
Dim response As String
response = proxy.EndDelayedResponse(result)


' Simple callback code
Dim proxy As localhost.Service1
Private Delegate Sub LabelDelegate( _
ByVal responseLabel As Label, _
ByVal response As String)

Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button7.Click
proxy = New localhost.Service1()
ClearForm()
Dim r As New Random()

proxy.BeginDelayedResponse(r.Next(1, 10000), _
New AsyncCallback(AddressOf Me.ServiceCallback), _
Label1)
proxy.BeginDelayedResponse(r.Next(1, 10000), _
New AsyncCallback(AddressOf Me.ServiceCallback), _
Label2)
proxy.BeginDelayedResponse(r.Next(1, 10000), _
New AsyncCallback(AddressOf Me.ServiceCallback), _
Label3)
End Sub

Private Sub ServiceCallback(ByVal result As IAsyncResult)
Dim response As String
response = proxy.EndDelayedResponse(result)
Dim responseLabel As Label = result.AsyncState
responseLabel.Invoke( _
New LabelDelegate(AddressOf Me.DisplayResponses), _
New Object() {responseLabel, response})
End Sub

Private Sub DisplayResponses(ByVal responseLabel As Label, _
ByVal response As String)
responseLabel.Text = response
Form1.ActiveForm.Refresh()
End Sub


reference: http://msdn.microsoft.com/en-us/library/aa480512.aspx


Windows LiveT Hotmail is faster and more secure than ever. Learn more.

0 comments:

Post a Comment

<--nothing-->