I would like to ask why this two approaches are different and returns two different set of values:
The first one which is correct in my opinion return values from 0 to 8 and works on different threads (LINQPad code):
void Main() { var newTasks = Enumerable.Range(0, 9).Select(x => Task.Run(() => DoSomething(x))); Task.WhenAll(newTasks); } public int DoSomething(int value) { return value; }
Second, which is not correct in my opinion which returns random values a specially 9 but also works on different threads.
void Main() { var tasks = new List<Task<int>>(); for (var index = 0; index < 9; index++) { var task = Task.Run(() => DoSomething(index)); tasks.Add(task); } Task.WaitAll(tasks.ToArray()); } public int DoSomething(int value) { return value; }
Is it possible to modify the second one and get the result similar to first example?
Thanks for your answers.