Please see the code below, which I have adapted from the following webpage: http://www.codeguru.com/csharp/csharp/introduction-to-async-and-await-keywords-in-c-5.0.htm
Public Class Form1
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
End Class
Class Program
Public Async Function PrintSumAsync() As Task
Dim value1 As Integer = Await GetValueAsync()
Dim value2 As Integer = Await GetValueAsync()
Console.WriteLine("Sum of two random numbers is: {0}", value1 + value2)
End Function
Private Async Function GetValueAsync() As Task(Of Integer)
System.Threading.Thread.Sleep(5000)
Dim random As Integer = ComputeValue()
Return random
End Function
Private Function ComputeValue() As Integer
MsgBox("got here 2")
Return New Random().[Next](1, 1000)
End Function
End Class
I have added a call to Sleep in the GetValueAsync so that it takes a while to finish.
I expected the code to reach msgbox1 (got here 1) before msgbox2 (got here 2). Await seems to stop the main thread. What am I missing? I don't have any experience with the newish await keyword. I upgraded from .net 3.5 to .NET 4.5.2 recently.
Update Based on Davids answer I have edited the code as follows:
Public Class Form1
Private Async Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
test()
MsgBox("got here 1")
End Sub
Public Async Sub test()
Dim program As New Program()
Await program.PrintSumAsync()
'Dim task As Task = program.PrintSumAsync()
MsgBox("got here 2")
End Sub
End Class
Class Program
Public Async Function PrintSumAsync() As Task
Dim value1 As Integer = Await GetValueAsync()
Dim value2 As Integer = Await GetValueAsync()
Console.WriteLine("Sum of two random numbers is: {0}", value1 + value2)
End Function
Private Async Function GetValueAsync() As Task(Of Integer)
Try
Await Task.Delay(5000)
Dim random As Integer = ComputeValue()
Return random
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Function
Private Function ComputeValue() As Integer
MsgBox("got here 2")
Return New Random().[Next](1, 1000)
End Function
End Class
How can I stop the main thread from finishing before message box 2 appears?
See Question&Answers more detail:os