Hi i am currently working through the study literature for my MCP. However i have noticed an issue whereby the TaskFactory does not behave as described in the literature. I don't suppose you could help it would be appreciated!

Code as below:

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;

namespace Chapter1
{
public static class Program
{

public static int test(int thisval)
{
Thread.Sleep(1000 * thisval);

return thisval;
}


public static void Main()
{

Task<Int32[]> parent = Task.Run(() =>
{
var results = new Int32[3];


TaskFactory tf = new TaskFactory(TaskCreationOptions.AttachedToParent, TaskContinuationOptions.ExecuteSynchronously);

tf.StartNew(() =>
{
results[0] = Program.test(10);
});

tf.StartNew(() =>
results[1] = Program.test(20));

tf.StartNew(() =>
results[2] = Program.test(30));

return results;

});




var finaltask = parent.ContinueWith(
parentTask =>
{
foreach (int i in parentTask.Result)
{
Console.WriteLine(i);
}
});

finaltask.Wait();


}
}
}


The PROBLEM is that the ContinueWith is called before all of the tasks within the task factory have completed causing it to print 0, 0 , 0 to the console.

If i change the code to be very very quick operations it works fine for example

tf.StartNew(() =>
{
results[0] =10;
});

However i think this is because the operation is just completing very very quickly. It seems to be hitting the return and running the continuewith operation and not waiting for the taskfactory tasks.

If i change the code to

tf.StartNew(() =>
{
results[0] = Program.test(10);
}).Wait();

for each releavnt line then it works fine, however it does all of these in order rather than synchronously.

In the book it says 'The finalTask only runs after the parent Task is finished, and the parent Task finished when all three children are finished.'

I was unable to find relevant help on MSDN for this.

Thanks in advance

Ian Woolfenden