Tony Dong
Tony Dong

Reputation: 3313

Use 'async' and 'await' in VB.net without return needed

I have a web application and need copy a batch of files from one file share server to another after a button click, async and awit seems to be a good way for this. I am not sure do I need Task.Run here? Is RunMoving() better move into another class for performance?

Here is my VB.NET code as following:

Public Sub FileMoving()
    PdfsMovingAsync()
    DoSomethingElse()
End Sub

Private Async Sub PdfsMovingAsync()
    Await Task.Run(Sub() RunMoving())
End Sub

Private Sub RunMoving()
    'Thread.Sleep(2000)
End Sub

Upvotes: 1

Views: 3952

Answers (1)

Nkosi
Nkosi

Reputation: 246998

PdfsMovingAsync should return Task. You want to avoid Async Subs.

Since DoSomethingElse is not dependent on PdfsMovingAsync completing first then they can run simultaneously.

Public Sub FileMoving()
    PdfsMovingAsync()
    DoSomethingElse()
End Sub

Private Function PdfsMovingAsync() As Task
    Return Task.Run(Sub() RunMoving())
End Function 

Await should ideally be used to actually await a function if something is dependent on it finishing first.

Reference Async/Await - Best Practices in Asynchronous Programming

Upvotes: 2

Related Questions