I have some simple code in which the main Thread is creating a new Task. The task in turn spawns multiple child tasks. The main Thread does a 'wait' on the parent Task. I'm observing that I don't get the same output across multiple runs of the program. In the code below I'm printing out the value of the iteration variable in each task but across different runs only subsets get printed out. I understand that the execution is not ordered but it would still have to be complete in that I'm expecting 100 numbers to get printed out(in no particular order). Does calling Wait does not wait for all child tasks to complete? I'm running VS2010 Team system Beta1
static void Main(string[] args)
{
Console.WriteLine("Main executing on ThreadID:- " + Thread.CurrentThread.ManagedThreadId.ToString());
var task = Task.Factory.StartNew(WriteNumbers);
task.Wait();
}
private static void WriteNumbers()
{
Console.WriteLine("WriteNumbers executing on ThreadID:- " + Thread.CurrentThread.ManagedThreadId.ToString());
for (int i = 0; i < 100; i++)
{
int localInt = i;
Task.Factory.StartNew(() =>
{
Write(localInt);
}, TaskCreationOptions.DetachedFromParent);
}
}
private static void Write(int i)
{
Console.WriteLine("Worker Thread executing on ThreadID:-" + Thread.CurrentThread.ManagedThreadId.ToString() + " Value:" + i.ToString());
}