Skip to content
Async/Await
step 1/5

Reading — step 1 of 5

Learn

~2 min readModules, Generics, Async

VB.NET 11+ has full async/await — same model as C#.

Basic async

Imports System.Net.Http
Imports System.Threading.Tasks

Async Function FetchDataAsync(url As String) As Task(Of String)
    Using client = New HttpClient()
        Return Await client.GetStringAsync(url)
    End Using
End Function

Async Function MainAsync() As Task
    Dim data = Await FetchDataAsync("https://example.com")
    Console.WriteLine(data.Length)
End Function

Key keywords

  • Async — marks a method as asynchronous; allows Await inside
  • Await — wait for a Task without blocking the thread
  • Task / Task(Of T) — represents async work
  • Function ... As Task(Of T) — returns a value asynchronously
  • Sub ... As Task — returns nothing asynchronously (use Function ... As Task if possible)

Calling async from Main

Module Program
    Sub Main()
        MainAsync().Wait()        ' or .GetAwaiter().GetResult()
    End Sub

    Async Function MainAsync() As Task
        Dim result = Await ComputeAsync()
        Console.WriteLine(result)
    End Function
End Module

Or use Async Sub Main (.NET Core+):

Async Function Main() As Task
    ' ...
End Function

Parallel async

Dim t1 = FetchAsync("url1")
Dim t2 = FetchAsync("url2")
Dim t3 = FetchAsync("url3")

Dim results = Await Task.WhenAll(t1, t2, t3)
' All three run concurrently; results is an array of 3 strings

Dim winner = Await Task.WhenAny(t1, t2, t3)
' First to complete

Cancellation

Imports System.Threading

Async Function SlowOpAsync(token As CancellationToken) As Task(Of Integer)
    For i = 1 To 10
        token.ThrowIfCancellationRequested()
        Await Task.Delay(100, token)
    Next
    Return 42
End Function

Dim cts = New CancellationTokenSource()
cts.CancelAfter(500)        ' cancel after 500ms
Try
    Dim result = Await SlowOpAsync(cts.Token)
Catch ex As OperationCanceledException
    Console.WriteLine("cancelled")
End Try

Common patterns

Async file I/O:

Imports System.IO

Using reader As New StreamReader("data.txt")
    Dim text = Await reader.ReadToEndAsync()
End Using

Async loops with collections:

For Each url In urls
    Dim data = Await FetchAsync(url)
    Process(data)
Next
' Sequential — each waits for previous

' For parallelism:
Dim tasks = urls.Select(Function(u) FetchAsync(u))
Dim results = Await Task.WhenAll(tasks)

Why async in VB.NET

The same reasons as in any language:

  • Don't block threads on I/O (HTTP, DB, file)
  • Scale to many concurrent operations
  • Keep UIs responsive
  • Compose async pipelines

VB.NET adopted async/await around 2012 (alongside C# 5). Most modern VB.NET enterprise code uses it heavily, especially for ASP.NET / Web API code.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…