Assume we have an array of tasks (called 'tasks') and then convert it to a list (called 'temp') by saying:
var temp = tasks.ToList();
What happens to those running tasks to which the array elements point? Do we have two sets of tasks running separately (one in the 'tasks' and the other in 'temp')? Or they point to the same tasks?
The following code (taken from the book Exam Ref 70-483 ) is relevant to what I'm saying (the last three lines):
Task<int>[] tasks = new Task<int>[3];
tasks[0] = Task.Run(() => { Thread.Sleep(2000); return 1; });
tasks[1] = Task.Run(() => { Thread.Sleep(1000); return 2; });
tasks[2] = Task.Run(() => { Thread.Sleep(3000); return 3; });
while (tasks.Length > 0) {
int i = Task.WaitAny(tasks);
Task<int> completedTask = tasks[i];
Console.WriteLine(completedTask.Result);
var temp = tasks.ToList();
temp.RemoveAt(i);
tasks = temp.ToArray();
}
UPDATE: I know the purpose of the last three lines but do not know why it work.