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
Task
– for Sub procedures (no result).Task(Of T)
– for Functions that return a value of typeT
.ValueTask(Of T)
– for high‑frequency scenarios to reduce allocations.
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
- Avoid blocking calls (
.Result
,.Wait()
) inside async methods. - Prefer
ConfigureAwait(False)
in library code to prevent deadlocks. - Keep async all the way down – if you call an async method, make the caller async.
- Use
Using
statements to dispose ofHttpClient
orStream
objects. - Document cancellation behavior for library consumers.
Sample Projects
Explore the full source on GitHub: