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()
?)
I'm pretty sure it's a safe operation even with the warning, but if you really wanted to get around it a better option than creating your own implementation would be just to convert your tasks
parameter into the type it wants:
Task.WaitAll(tasks.Cast<Task>().ToArray())
That kills the blue squiggles for me, lets me keep my tasks
variable generic and doesn't force me to create a whole lot of new scary code that's ultimately unnecessary.