Mike Henry
Mike Henry

Reputation: 2441

How should Task.Run call an async method in VB.NET?

Given an asynchronous method that does both CPU and IO work such as:

Public Async Function RunAsync() As Task
    DoWork()
    Await networkStream.WriteAsync(buffer, 0, buffer.Length).ConfigureAwait(False)
End Function

Which of the following options is the best way to call that asynchronous method from Task.Run in Visual Basic and why?

Which is the VB equivalent for C# Task.Run(() => RunAsync())?

Await Task.Run(Function() RunAsync())
' or
Await Task.Run(Sub() RunAsync())

Are the Async/Await keywords within Task.Run necessary or redundant? This comment claims they're redundant, but this answer suggests it might be necessary in certain cases:

Await Task.Run(Async Function()
                   Await RunAsync()
               End Function)

Is ConfigureAwait useful within Task.Run?

Await Task.Run(Function() RunAsync().ConfigureAwait(False))

Await Task.Run(Async Function()
                   Await RunAsync().ConfigureAwait(False)
               End Function)

Which of the above 5 Task.Run options is best practice?

Note: There's a similar question How to call Async Method within Task.Run? but it's for C#, the selected answer has negative votes, and doesn't address ConfigureAwait.

Upvotes: 14

Views: 49997

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456322

Which is the VB equivalent for C# Task.Run(() => RunAsync())?

My VB is horribly rusty, but it should not be the Sub one, so I'd go with:

Task.Run(Function() RunAsync())

Are the Async/Await keywords within Task.Run necessary or redundant?

I have a blog post on the subject. In this case, they're redundant because the delegate is trivial.

Is ConfigureAwait useful within Task.Run?

Only if you do an Await.

Upvotes: 28

Related Questions