ReWrite: I have stripped the question down to contain the example code instead of a link to it and the results and question as the surrounding information seemed to be causing confusion.
Question: Why do tasks seem to start with out being started?
This is a piece of sample code from the Microsoft Website on tasks. It is described as creating an unstarted task, creating a second started task and waiting for it to complete, then starting the first task and finally starting a third task synchronously in the main thread.
Here is an uncommented version of the sample code:
using System;
using System.Threading;
using System.Threading.Tasks;
class StartNewDemo
{
static void Main()
{
Action<object> action = (object obj) =>
{
Console.WriteLine("Task={0}, obj={1}, Thread={2}", Task.CurrentId, obj.ToString(), Thread.CurrentThread.ManagedThreadId);
};
Task t1 = new Task(action, "alpha");
Task t2 = Task.Factory.StartNew(action, "beta");
t2.Wait();
t1.Start();
Console.WriteLine("t1 has been launched. (Main Thread={0})", Thread.CurrentThread.ManagedThreadId);
t1.Wait();
Task t3 = new Task(action, "gamma");
t3.RunSynchronously();
t3.Wait();
}
}
Here are the results:
Task=1, obj=beta, Thread=3
t1 has been launched. (Main Thread=1)
Task=2, obj=alpha, Thread=3
Task=3, obj=gamma, Thread=1
From the description task 1, which is Beta, should be ran only after task 2 has completed so the main thread can progress. This does not seem to be the case from this output. I also ran a second test run where I put a display of the tick counts into the action object and received this, confirming that Task1 is indeed starting before Task2 is completed.
Task=1, obj=beta, Thread=3 (634529151744201906)
t1 has been launched. (Main Thread=1)
Task=2, obj=alpha, Thread=3 (634529151744221908)
Task=3, obj=gamma, Thread=1 (634529151744221908)
I am not trying to do anything fancy here, I am simply looking for an explanation as to why Task1 (obj=beta) is apparently executing before it is given the instruction to do so.
Task=1 is slightly misleading here, as this is actually t2 in the sample code. You can see this because ‘beta’ is present. It is started and completed before running t1.
This is t1 (with Id 2).
This is t3.