I get IEnumerable<Task> tasks from somewhere that I do not control. I do not know if tasks are created manually using new Task , Task.Run or if they are the result of calling the async method of the async Task DoSomethingAsync() .
If I do await Task.WhenAll(tasks) , I risk hanging endlessly because maybe one or more tasks are not starting.
I cannot do tasks.ForEach(t => t.Start()) because then I will get an InvalidOperationException. "Start cannot be called into the promise style task" if it is called by calling the async method (already running).
I cannot do await Task.WhenAll(tasks.Select(t => Task.Run(async () => await t))) , because every t still does not start, just waiting for it.
I believe the solution has something to do with checking each Status and Start() task based on this, but I also assume that it can be tricky, as this status can change at any time, right? If this is still the way, what statuses would be correct for verification, and what kind of threading problems should I bother with?
Example of a non-working example:
An example of a working case:
//calls the async function, starting it. Task t = DoSomethingAsync(); IEnumerable<Task> tasks = new[] {t}; //here I receive the tasks and it will complete because the task is already started await Task.WhenAll(tasks); async Task DoSomethingAsync() => Console.WriteLine("started");
source share