How to Implement Async - Await Function
I guess the reason you want to use Async / Await is to perform asynchronous processing without blocking the UI. But the way you have set it up looks like it will block the UI anyway. Here is an example which demonstrates how you can call a method without blocking, and with blocking
Private Async Sub btnSubMain_Click(sender As Object, e As EventArgs) Handles btnSubMain.Click
Dim answer As Integer
Try
btnSubMain.Enabled = False
' async call, UI continues to run
answer = Await SomeIntegerAsync()
Finally
btnSubMain.Enabled = True
End Try
MessageBox.Show(answer.ToString())
Try
btnSubMain.Enabled = False
' synchronous call, UI is blocked
answer = SomeInteger()
Finally
btnSubMain.Enabled = True
End Try
MessageBox.Show(answer.ToString())
End Sub
Function SomeIntegerAsync() As Task(Of Integer)
Return Task.Run(AddressOf SomeInteger)
End Function
Function SomeInteger() As Integer
Thread.Sleep(5000)
Return 34
End Function
The first thing to note is that the UI event handler is marked Async
, so the awaiting is done in that method. It will be clear to most that your intent is to allow something to happen without blocking the UI. Since it is marked that way, it must contain Await
. I have written two functions, one which returns a task and has Async in the name, and another which just returns the integer, without Async in the name.
I call both in the button click handler. The first call will allow the UI to run smoothly while calling the function. You can check that by moving the window around after clicking. The second calls the function directly and blocks the UI. This is a basic design you can follow.
A comment on your question notes you could use Task.Delay
but I think sleeping the thread is a good way to simulate long running code which you don't want to block the UI so it makes sense as a demonstration.