Is there a generic Task.WaitAll?

Cristian Lupascu picture Cristian Lupascu · Apr 6, 2012 · Viewed 11k times · Source

I start a few parallel tasks, like this:

var tasks =
    Enumerable.Range(1, 500)
    .Select(i => Task.Factory.StartNew<int>(ProduceSomeMagicIntValue))
    .ToArray();

and then join them with

Task.WaitAll(tasks);

On this last line I get a blue squiggly marker under tasks, with a warning message:

Co-variant array conversion from Task[] to Task[] 
can cause run-time exception on write operation.

I understand why I get this message, but is there a way around that? (for example, like a generic version of Task.WaitAll()?)

Answer

MerickOWA picture MerickOWA · Apr 6, 2012

A generic method of Task.WaitAll would imply that all Tasks would have to return the same type which would be extremely limited usefulness. Writting something like that could be done manually (see Bas Brekelmans answer), but this wont allow ContinueWith or cancellation without alot of work.

A simple solution if you aren't using the array for anything else is

  .ToArray<Task>();