1

I have a collection of Task<string>. I'd like to get the return value of a Task that first returns a non-null value.

If I use Task.WhenAny, I can get the return value of the Task that first completed its execution, but it's impossible to exclude null values.

private static async Task<string> FirstRespondingTaskAsync(IEnumerable<Task<string>> tasks)
{
    var completedTask = await Task.WhenAny(tasks);
    var data = await completedTask;
    // data can be null, which I'd like to exclude
    return data;
}

If I use Task.WhenAll, it's possible to exclude null values, but I have to wait for all tasks to complete its execution.

private static async Task<string> FirstNonNullTaskAsync(IEnumerable<Task<string>> tasks)
{
    var all = await Task.WhenAll(tasks);
    // I have to wait until all tasks complete
    var data = all.FirstOrDefault(s => s != null);
    return data;
}

How can I get the first value that satisfies a specific condition out of multiple tasks?

user4134476
  • 385
  • 4
  • 22

0 Answers0