Asynchronous Programming in Visual Basic
Asynchronous programming helps you keep your applications responsive while performing long‑running operations, such as I/O, network calls, or CPU‑intensive work. In Visual Basic, the Async
and Await
keywords provide a simple and clear way to write asynchronous code.
Key Concepts
- Task – Represents an asynchronous operation.
- Async Function/Method – Declared with the
Async
modifier and returnsTask
orTask(Of T)
. - Await – Suspends execution until the awaited task completes, without blocking the thread.
Simple Example
Imports System.Net.Http
Imports System.Threading.Tasks
Public Class Example
Public Async Function GetWebContentAsync(url As String) As Task(Of String)
Using client As New HttpClient()
Dim response As HttpResponseMessage = Await client.GetAsync(url)
response.EnsureSuccessStatusCode()
Return Await response.Content.ReadAsStringAsync()
End Using
End Function
Public Async Sub ShowResult()
Dim content As String = Await GetWebContentAsync("https://example.com")
Console.WriteLine(content)
End Sub
End Class
This code fetches a web page without freezing the UI thread. The Await
keyword ensures that the method returns to its caller while the request is in progress.
When to Use Async/Await
- UI applications that must stay responsive.
- Server‑side code that should free threads for other requests.
- Any I/O‑bound operation where latency is expected.