Monday, March 17, 2014

Calling an asynchronous method

.NET 4 included a programming model and a few extra operators (await and async) to support asynchronous programming.  Even if you're not interested in doing anything asynchronously, there are certain classes in .NET that only offer asynchronous methods.  An asynchronous method can be identified by 3 things:
  1. The Async operator in the method signature.
  2. The word Async in the method name.  (This is only a standard and is not enforced)
  3. A return type of Task or Task(Of TResult).
An asynchronous method can only be called from another asynchronous method.  The method or event handler you are calling it from must be designated with the Async operator.

As an example, we are going to call the GetStringAsync method of the HttpClient class.

    Private Async Sub ButtonKickOff_Click(sender As Object, e As EventArgs) Handles ButtonKickOff.Click

        Dim Client As New System.Net.Http.HttpClient

        TextBoxResults.Text = Await Client.GetStringAsync("http://www.google.com")

    End Sub

This event handler is from a Windows Forms application.  Note that I added the Async operator to the event signature.  In this case, I'm calling the asynchronous function in a synchronous way, so I simply use the Await operator to signal that I'm just going to wait until it completes.

    Private Async Sub ButtonKickOff_Click(sender As Object, e As EventArgs) Handles ButtonKickOff.Click

        Dim Client As New System.Net.Http.HttpClient

        Dim Results As System.Threading.Tasks.Task(Of String) = _
            Client.GetStringAsync("http://www.google.com")

        LabelStatus.Text = "Processing..."

        TextBoxResults.Text = Await Results

    End Sub

Here, I am calling GetStringAsync and while it is executing, I am moving on. I immediately display a message to the user and then wait for the result.

No comments:

Post a Comment