Aaron Aaron - 1 year ago 172
Vb.net Question

New to Async/Await, does this run async?

I typically multithread through older methods(Threading, Invoke, etc). I've looked through a lot of documentation, and have come up with the below.

The reason for this post is that I have seen literally hundreds of threads on here where people say, "Why did you do that? It's running synchronously anyway." I do not have the confidence based upon my prior reading to assume this is correct and running asynchronously. It is not difficult code, and it looks right to me - just need a 'yes' or 'no' and if 'no,' an explanation would be great. Thanks in advance.

Program sends contracts in a loop. If the pdfs go to a fax line, we need to wait 15 seconds in between sending to the same number. The timer/class logic gets kind of complex, but for this purpose, just know that I have a List(of Class) that cleans itself once done. Once the list is empty, I'm firing an event to update the GUI.

GUI Thread - call

Private Async Sub ProcessIt(ByVal oList As List(Of String))
'Code that sends emails, or creates the queue class and adds it to queue.
Dim bWait As Boolean = Await WaitOnQueue()
RaiseEvent ProcessComplete(ErrorList, Nothing)
End Sub

"Awaitable" Function (I think)

Private Async Function WaitOnQueue() As Task(Of Boolean)
While oQueue.Count > 0
Await Task.Delay(500)
End While
Return True
End Function

I've stripped code that is unnecessary to make this as simple as possible to evaluate. Is this running async or on the GUI thread? Thanks again in advance.

Answer Source

To be clear, adding the async keyword to a method does not make the method asynchronous (as it seems you have assumed). It means that you're allowed to use the await keyword inside of the method.

Regarding Task.Delay - it is intended to run asynchronous. Task.Delay gives you a logical delay without blocking the current thread.

However in your example, Task.Delay is making your method still do its CPU bound work in the UI thread. If your goal is to do some work off the UI thread, then you can use await Task.Run to run it on a threadpool thread and (asynchronously) get the result of the method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download