There's a question from a few years back How to WhenAll when some tasks can be null? which has a fairly simple top-rated answer:
Task task1 = null
await Task.WhenAll(new Task[] { task1, task2, task3 }.Where(i => i != null));
But in modern .Net 6 we have NRTs and this causes compiler warnings because you are putting Task?
inside an array of Task
.
If you simply update this to:
await Task.WhenAll(new Task?[] { task1, task2, task3 }.Where(i => i != null));
You still get a warning because Task.WhenAll
doesn't accept Task?
. What is the modern NRT version of the referenced solution?
MRE here: https://dotnetfiddle.net/R2SN43
using System;
using System.Threading.Tasks;
using System.Linq;
#nullable enable
public class Program
{
public static async void Main()
{
Task? task1 = null;
Task? task2 = null;
Task? task3 = null;
await Task.WhenAll(new Task?[] { task1,task2,task3 }.Where(t => t is not null));
}
}
This is not a question about converting a list of NRTs to non-nullable. It is a question about Tasks that may not be run. Ending up with a list of nullable Tasks is a symptom, not the specific problem... as one commenter has mentioned we might avoid having null values entirely.