C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: Async and Await help with reading a file with StreamReader or downloading from the network.
Task: We use Task, a generic type, to Start and Wait for an asynchronous action (a task) to complete.
Start, wait: In Main we invoke Start and Wait on the task. The program does not exit until ProcessDataAsync finishes.
Async: This keyword is used at the function level. The ProcessDataAsync Sub is Async. It contains a usage of Await.
Await: This keyword, found in an Async Sub, causes the method to pause until the task (an argument to Await) is finished.
SubVB.NET program that uses Async, Await, Task
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 Module
Output: initial
HandleFile enter
Please wait, processing
Output: final
HandleFile enter
Please wait, processing
HandleFile exit
Count: 1916146
Note: The For-loop in HandleFileAsync is meant to take a long time. This demonstrates the benefit of Async and Await.
For Each, ForSo: 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.