So here is my code
Task<int[]> parent = Task.Run(() => { var result = new int[3]; TaskFactory tf = new TaskFactory(TaskCreationOptions.AttachedToParent, TaskContinuationOptions.ExecuteSynchronously); for (int i = 0; i < result.Length; i++) { int j = i; tf.StartNew(() => result[j] = GetRandomNumber(j)); } return result; }); var finalTask = parent.ContinueWith(parentTask => { foreach (var i in parentTask.Result) { Console.WriteLine(i); } }); finalTask.Wait();
Basically I create 3 Task , which are children of Task called parent (I think). I am considering a parent task in order to wait for the completion of all three child tasks. After that, finalTask will wait for execution due to finalTask.Wait(); of this statemant. But everything is not going as expected. I mean, the application exits before any of the GetRandomNumber calls GetRandomNumber . Part of the code here is copied from a book stating that these parent tasks should wait for the completion of the child task, which apparently does not happen. Did I miss something?
this is what GetRandomNumber does
public static int GetRandomNumber(int ii) { Random rand = new Random(); for (int i = 0; i < 1000000000; i++) { }
This code does the same.
Task<int[]> parent = Task.Run(() => { var result = new int[3]; for (int i = 0; i < result.Length; i++) { int j = i; new Task(() => result[j] = GetRandomNumber(j), TaskCreationOptions.AttachedToParent).Start(); } return result; });
Dimitri
source share