Asynchronous Programming with Async and Await - Visual ...
Asynchronous Programming with Async and Await - Visual ...
If you want to learn more, please visit our website Asynchronous Machines.
Asynchronous programming with Async and Await (Visual Basic)
- Article
- 09/21/2022
In this article
Asynchronous programming can improve your application's performance and responsiveness. However, traditional methods for writing asynchronous code are often complex, making the code hard to write, debug, and maintain. Visual Studio 2012 introduced a simplified approach that leverages asynchronous support in .NET Framework 4.5 and higher, as well as the Windows Runtime. The compiler handles the complex aspects, maintaining a logical structure similar to synchronous code.
This article provides an overview of when and how to use async programming, with links to support topics containing more detailed information and examples.
Async improves responsiveness
Asynchronous processes are essential for tasks that might block the application, such as web access. Accessing a web resource can sometimes be slow or delayed. In a synchronous process, the entire application would wait, but an asynchronous process allows the application to perform other tasks while waiting for the web resource.
Asynchronous programming is especially valuable for applications that access the UI thread, which usually operates on a single thread. Using asynchronous methods, the application remains responsive and can be interacted with by the user, such as resizing or minimizing the window.
This approach to asynchronous programming offers benefits similar to an automatic transmission in a car, simplifying the developer's efforts while providing all the gains of traditional asynchronous methods.
Async methods are easier to write
The Async
and Await
keywords in Visual Basic are central to async programming. Using these keywords, you can create asynchronous methods as easily as synchronous ones. Methods defined with Async
and Await
are known as async methods.
The following example shows an async method. Most of the code will look familiar, with comments highlighting features that make the method asynchronous:
' Example of an Async Function
' The function has an Async modifier.
' Its return type is Task or Task(Of T).
' The name ends in "Async" by convention.
Async Function AccessTheWebAsync() As Task(Of Integer)
Using client As New HttpClient()
Dim getStringTask As Task(Of String) = client.GetStringAsync("https://learn.microsoft.com/dotnet")
DoIndependentWork()
Dim urlContents As String = Await getStringTask
Return urlContents.Length
End Using
End Function
If AccessTheWebAsync
has no work to do during the call to GetStringAsync
, you can simplify the code by calling and awaiting in a single statement:
Dim urlContents As String = Await client.GetStringAsync()
Characteristics of an async method:
- The method signature includes an
Async
modifier. - The name ends with an "Async" suffix, by convention.
- The return type is typically
Task(Of TResult)
orTask
. - The method includes at least one await expression, suspending the method until the awaited asynchronous operation completes.
In async methods, you use keywords and types to express your intent, and the compiler manages the details. This simplifies tasks like loops and exception handling compared to traditional asynchronous code.
What happens in an Async method
Understanding how control flows in asynchronous programming is crucial. The following steps outline the process:
- An event handler calls and awaits the
AccessTheWebAsync
async method. AccessTheWebAsync
creates an HttpClient instance and calls theGetStringAsync
method to download a website's content.GetStringAsync
may suspend its progress, possibly waiting for a website.GetStringAsync
yields control toAccessTheWebAsync
, returning aTask(Of String)
.AccessTheWebAsync
can continue other tasks not dependent on the result fromGetStringAsync
.DoIndependentWork
is a synchronous method that completes its task and returns control.AccessTheWebAsync
suspends its progress at theAwait
operator, yielding control to its caller and returning aTask(Of Integer)
.GetStringAsync
completes and stores the result in thegetStringTask
.AccessTheWebAsync
retrieves the string result using theAwait
operator and calculates the length of the string.
In asynchronous programming, a synchronous method returns when its work is complete. An async method returns a task value when its work is suspended. When the async method completes, the task is marked as completed.
API Async Methods
There are numerous methods in .NET Framework 4.5 or higher that support async programming, marked with an "Async" suffix and returning a task type. The System.IO.Stream
class, for example, includes CopyToAsync
, ReadAsync
, and WriteAsync
.
Threads
Async methods are non-blocking. An Await
expression in an async method doesn't block the current thread but returns control to the caller. The Async
and Await
keywords don't create additional threads; rather, the method runs on the current synchronization context.
This async approach is generally better than traditional methods like BackgroundWorker for I/O-bound operations, as the code is simpler and less prone to errors. For CPU-bound operations, combining async programming with Task.Run
is more effective.
Async and Await
Using the Async
modifier allows methods to use Await
to mark suspension points. The await operator tells the compiler that the async method can't continue until the awaited process completes.
Even without Await
expressions, the method will execute like a synchronous method but with a compiler warning.
Return types and parameters
An async method typically returns a Task
or Task(Of TResult)
. Inside the method, Await
is applied to a task returned from another async method. You use Task(Of TResult)
if the method returns a value and Task
if it doesn't.
Example declarations and calls for methods that return Task(Of TResult)
or Task
:
Async Function TaskOfTResult_MethodAsync() As Task(Of Integer)
Dim hours As Integer
' . . .
Return hours
End Function
Dim returnedTaskTResult As Task(Of Integer) = TaskOfTResult_MethodAsync()
Dim intResult As Integer = Await returnedTaskTResult
' or, in a single statement
Dim intResult As Integer = Await TaskOfTResult_MethodAsync()
Async Function Task_MethodAsync() As Task
' . . .
End Function
Dim returnedTask = Task_MethodAsync()
Await returnedTask
' or, in a single statement
Await Task_MethodAsync()
Each returned task represents ongoing work. An async method can also be a Sub
method, primarily used for event handlers, which can't be awaited, and exceptions can't be caught by the caller.
Naming convention
By convention, append "Async" to the names of methods with an Async
modifier. This convention does not apply to common event handlers, such as Button1_Click
.
Complete Example
The following code is from the MainWindow.xaml.vb file of a Windows Presentation Foundation (WPF) application:
Imports System.Net.Http
Class MainWindow
Private Async Sub StartButton_Click(sender As Object, e As RoutedEventArgs)
Dim contentLength As Integer = Await AccessTheWebAsync()
ResultsTextBox.Text &= $"{vbCrLf}Length of the downloaded string: {contentLength}.{vbCrLf}"
End Sub
Async Function AccessTheWebAsync() As Task(Of Integer)
Using client As New HttpClient()
Dim getStringTask As Task(Of String) = client.GetStringAsync("https://learn.microsoft.com/dotnet")
DoIndependentWork()
Dim urlContents As String = Await getStringTask
Return urlContents.Length
End Using
End Function
Sub DoIndependentWork()
ResultsTextBox.Text &= $"Working . . . . . . .{vbCrLf}"
End Sub
End Class
Related Topics and Samples
For more information, refer to Async Sample: Example from "Asynchronous Programming with Async and Await".
If you are interested in learning more, visit our pages on Asynchronous Machines, the Why Slip Ring Is Used in Induction Motor, and Nema Standards for Electric Motors.
- Previous: What Is A Boat Slip? A Comprehensive Guide
- Next: None