4

I have a collection of generic Tasks those are marked for execution. As and when a task complete (using Task.WaitAny), I am adding it to an ObservableCollection.

But, the issue is at Task.WaitAny(...) line, which says Co-variant array conversion from Task<MyType>[] to Task[] can cause run-time exception on write operation.

I am fairly knowledgeable on what this exception means and why it complains at this stage.

Question: Is there any generic version of Task.WaitAny(), which can take Task<T> as parameter instead of Task[].

Thanks in advance.

code

chue x
  • 18,573
  • 7
  • 56
  • 70
S.N
  • 4,910
  • 5
  • 31
  • 51

2 Answers2

2

There is a generic Task.WhenAny

public static Task<Task<TResult>> WhenAny<TResult>(IEnumerable<Task<TResult>> tasks);
public static Task<Task<TResult>> WhenAny<TResult>(params Task<TResult>[] tasks);

await it to get the completed task.

Jakub Lortz
  • 14,616
  • 3
  • 25
  • 39
2

You can use Task.WhenAny which in your case will even simplify your code like this

var result = new ObservableCollection<LenderScoreCard>();
var parallelScoreList = parallelScore.ToList();
while (parallelScoreList.Count != 0)
{
    var completedTask = Task.WhenAny(parallelScoreList).Result;
    result.Add(completedTask.Result);
    parallelScoreList.Remove(completedTask);
}
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343