Async, Await. In asynchronous programming, many control flows can exist at once. With the Async and Await keywords in VB.NET we have a standard, clear way to program this way.
Threading is supported, but with Async and Await, we do not need multiple threads. Some actions are (like downloading from the network) are faster when done in an asynchronous way.
Imports System.IO
Module Module1
Sub Main()
' Create a Task with AddressOf.
Dim task = New Task(AddressOf ProcessDataAsync)
' Start and wait for task to end.
task.Start()
task.Wait()
Console.ReadLine()
End Sub
Async Sub ProcessDataAsync()
' Create a task Of Integer.' ... Use HandleFileAsync method with a large file.
Dim task As Task(Of Integer) = HandleFileAsync("C:\enable1.txt")
' This statement runs while HandleFileAsync executes.
Console.WriteLine("Please wait, processing")
' Use await to wait for task to complete.
Dim result As Integer = Await task
Console.WriteLine("Count: " + result.ToString())
End Sub
Async Function HandleFileAsync(ByVal file As String) As Task(Of Integer)
Console.WriteLine("HandleFile enter")
' Open the file.
Dim count As Integer = 0
Using reader As StreamReader = New StreamReader(file)
Dim value As String = Await reader.ReadToEndAsync()
count += value.Length
' Do a slow computation on the file.
For i = 0 To 10000 Step 1
Dim x = value.GetHashCode()
If x = 0 Then
count -= 1
End If
Next
End Using
Console.WriteLine("HandleFile exit")
Return count
End Function
End ModuleHandleFile enter
Please wait, processingHandleFile enter
Please wait, processing
HandleFile exit
Count: 1916146
Some notes, HandleFileAsync. Please look at HandleFileAsync. This uses a StreamReader to open and read (in an asynchronous way) the specified file.
Some notes, task. When the Await keyword is encountered, control flow pauses until its Task finishes execution. So the "count" returned from HandleFileAsync is always ready to be printed.
Discussion. What is the benefit to Async and Await in the example program? The message "Please wait, processing" is displayed while the asynchronous task executes.
So Two control flows exist at once. In a real program, another important action could be taken instead of just printing a message.
Tip For the file "enable1.txt," you can substitute any large data file. This is a list of words that is about 2 megabytes.
Summary. In .NET many types like StreamReader and HttpClient have asynchronous features. With Async and Await we exploit these features to improve program responsiveness.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 12, 2024 (simplify).