Monday, April 23, 2012

Why TaskFactory.StartNew Task is not starting immediately?

As per the MSDN Documentation TaskFactory.StartNew it Creates and starts a Task. So, for the below code sample



class Program
{
public static void Main()
{
var t =Task.Factory.StartNew(
() => SomeLongRunningCalculation(10, Display)
);
var t1 = Task.Factory.StartNew(
() => SomeLongRunningCalculation(20, Display)
);
Console.WriteLine("Invoked tasks");
Task.WaitAll(t, t1);
Console.ReadLine();
}

public static void Display(int value)
{
Console.WriteLine(value);
}

public static void SomeLongRunningCalculation(int j, Action<int> callBack)
{
Console.WriteLine("Invoking calculation for {0}", j);
System.Threading.Thread.Sleep(1000);
if (callBack != null)
{
callBack(j + 1);
}
}
}


My expected output was




Invoking calculation for 10
Invoking calculation for 20
Invoked tasks
11
21



But, it is displaying




Invoked tasks
Invoking calculation for 20
Invoking calculation for 10
21
11



I would like to learn




  1. Why the tasks are not running immediately after StartNew?

  2. What should I do, to get the output in the expected format?





No comments:

Post a Comment