MSDN – VB.NET Asynchronous Programming

Table of Contents

Overview

Asynchronous programming in VB.NET allows you to keep UI threads responsive and improve scalability of server applications. The Async modifier marks a method that contains one or more Await expressions, enabling the compiler to rewrite the method as a state machine.

Async & Await Keywords

Use Async on a method, lambda, or Sub. Inside, place Await before a task‑returning operation. The compiler pauses the method, returns control to the caller, and resumes when the awaited task completes.

Public Async Function GetDataAsync(url As String) As Task(Of String)
    Using client As New HttpClient()
        Dim response = Await client.GetStringAsync(url)
        Return response
    End Using
End Function

Return Types

Error Handling

Exceptions thrown inside an async method are captured and placed on the returned task. Use Try…Catch inside the async method or handle the exception when awaiting.

Try
    Dim result = Await GetDataAsync(url)
    Console.WriteLine(result)
Catch ex As HttpRequestException
    Console.WriteLine($"Request failed: {ex.Message}")
End Try

Cancellation Tokens

Pass a CancellationToken to async operations to allow cooperative cancellation.

Public Async Function GetDataAsync(url As String, token As CancellationToken) As Task(Of String)
    Using client As New HttpClient()
        client.DefaultRequestHeaders.Add("User-Agent", "VBAsyncDemo")
        Dim response = Await client.GetStringAsync(url, token)
        Return response
    End Using
End Function

' Usage
Dim cts = New CancellationTokenSource()
Try
    Dim data = Await GetDataAsync("https://example.com", cts.Token)
    Console.WriteLine(data)
Catch ex As OperationCanceledException
    Console.WriteLine("Operation was cancelled.")
End Try

Best Practices

  1. Avoid blocking calls (.Result, .Wait()) inside async methods.
  2. Prefer ConfigureAwait(False) in library code to prevent deadlocks.
  3. Keep async all the way down – if you call an async method, make the caller async.
  4. Use Using statements to dispose of HttpClient or Stream objects.
  5. Document cancellation behavior for library consumers.

Sample Projects

Explore the full source on GitHub:

Related Articles