JimmyJimm JimmyJimm - 1 month ago 5
Vb.net Question

Diffrence between async/await and ContinueWith

Consider this example:

Private Async Function ComputeText() As Task(Of String)
Dim result As String = Await Task.Run(Function()
'do whatever

Return "Done"

End Function)

Return result
End Function


Now could anyone tell me whether there is diffrence between those two button event handlers? From my perspective this is the same but 'better approach' is to use the 1st one, am i right?

'1st:
Private Async Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
LabelCounter.Text = "Running"

Dim value As string = Await ComputeText()
LabelCounter.Text = value

End Sub

'2nd:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
LabelCounter.Text = "Running"

Dim task = ComputeText().ContinueWith(
Sub(x)
LabelCounter.Invoke(
Sub()
LabelCounter.Text = x.Result
End Sub)
End Sub)
End Sub

Answer

Await does use ContinueWith under the hood. However, ContinueWith is a dangerous API and should not be used directly. As I describe in my post on task continuations:

  • ContinueWith has an unfortunate choice of default sceduler; it uses TaskScheduler.Current rather than TaskScheduler.Default.
  • ContinueWith does not understand asynchronous delegates, so it will return an extra task wrapper that you have to unwrap (by calling Unwrap).
  • ContinueWith does not have appropriate default option arguments for asynchronous code (e.g., TaskContinuationOptions.DenyChildAttach and TaskContinuationOptions.ExecuteSynchronously).

For these reasons, you should use Await instead of ContinueWith for asynchronous code.

Also, it's shorter and prettier. :)