سؤال

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?

هل كانت مفيدة؟

المحلول

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

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

نصائح أخرى

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)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top