2

I have some VB.net code that goes like:

If (condition1) Then
    Dim Task1 = function1Async()
    Dim Task2 = function2Async()
    Await Task.WhenAll(Task1, Task2)
Else
    Dim Task1 = function1Async()
    Dim Task3 = function3Async()
    Await Task.WhenAll(Task1, Task3)
End If

But I would prefer to do something like:

Dim Task1 = function1Async()
Dim Task2 = New Task()
Dim Task3 = New Task()
If (condition1) Then
    Task2 = function2Async()
Else
    Task3 = function3Async()
End If
Await Task.WhenAll(Task1, Task2, Task3)

However, "New Task()" does not produce an awaitable task. Is there some sort of minimal awaitable task that I can create as a placeholder, in case the real task is not created later on?

Crono
  • 10,211
  • 6
  • 43
  • 75
Brent
  • 16,259
  • 12
  • 42
  • 42
  • Well you *can* have a task pointing to a sub that does nothing, but what you *really* should do is build a list of *real* tasks to be performed. – Crono Apr 30 '14 at 14:37
  • My real code is more complex, and it makes it much more maintainable to have a single Await statement at the end. – Brent Apr 30 '14 at 14:39
  • 1
    Possible duplicate http://stackoverflow.com/questions/13127177/if-my-interface-must-return-task-what-is-the-best-way-to-have-a-no-operation-imp – Todd Menier Apr 30 '14 at 18:51

2 Answers2

5

You shouldn't use the Task constructor for tasks in the asynchronous world.

You can create a completed task by calling Task.FromResult(0).

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • 2
    This should be the accepted answer as it incurs the least overhead and is [recommended](http://social.msdn.microsoft.com/Forums/en-US/fab0a26f-f5d6-4740-8bf0-4133fe1543bc/doing-nothing-in-async-methods) by Stephen Toub. – Todd Menier Apr 30 '14 at 18:53
  • Well this *does* answers the original question but the OP absolutely does not need blank tasks for what he's trying to do. – Crono May 01 '14 at 13:46
2

Since you ask, you can have a "blank" task that points to a dummy delegate. However, I think using a conditionally filled list of tasks instead would be much better and cleaner:

Dim TaskList As New List(Of Task)

TaskList.Add(function1Async())

If (condition1) Then
    TaskList.Add(function2Async())
Else
    TaskList.Add(function3Async())
End If

Await Task.WhenAll(TaskList)
Crono
  • 10,211
  • 6
  • 43
  • 75