Await
isn't stopping the main thread, you are:
System.Threading.Thread.Sleep(5000)
There's nothing asynchronous happening in this method:
Private Async Function GetValueAsync() As Task(Of Integer)
System.Threading.Thread.Sleep(5000)
Dim random As Integer = ComputeValue()
Return random
End Function
(I'm surprised the compiler isn't complaining about it. It does with C#.) So even though the method signature and consuming code is decorated with Async
and Await
keywords, the resulting code isn't actually asynchronous. It can be, however, if you await an asynchronous operation in that method. For example:
Private Async Function GetValueAsync() As Task(Of Integer)
Await Task.Delay(5000)
Dim random As Integer = ComputeValue()
Return random
End Function
This will make the entire stack of operations in question asynchronous, making full use of the new keywords.
Note, however, that the observed results will probably still be the same. Take a look at the top level method:
Private Async Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim program As New Program()
Await program.PrintSumAsync()
MsgBox("got here 1")
End Sub
The code in that method still isn't going to execute the third line until after the second line has been awaited until completion. The very top level (the UI invoking this handler) will continue without waiting on this method, but this method will wait until its asynchronous operations are complete before it continues.
In order to get the result you're looking for, you would want to capture the Task
instead of awaiting it. Something like this:
Private Async Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim program As New Program()
Dim task As Task = program.PrintSumAsync()
MsgBox("got here 1")
' do something with the task object.
' await it, provide it with a callback function for when it completes, etc.
End Sub
The Async
and Await
keywords don't necessarily make a function happen on a new thread. For most intents and purposes, you can very often think of them as simply syntactic shorthand for wrapping part of a method in a ContinueWith()
on a Task
object. In any given Async
method, there needs to be an Await
at which to place that ContinueWith()
. If there's no Await
within it, then the Async
method isn't asynchronous.