I have a list of 10 Tasks, each task takes 15 seconds. All the tasks are in an array and are executed asynchronously. Shouldn't the entire set take about 15 seconds? From the code below, notice that in the output the entire set takes 21 seconds. When I change it to 100 tasks, it takes over a minute. It's almost as if simply creating the task takes a second. What am I missing? Thanks!
static void Main(string[] args)
{
var mainStart = DateTime.Now;
var tasks = new List<Task>();
for (int i = 0; i < 10; i++)
{
tasks.Add(Task.Factory.StartNew((Object data) =>
{
var index = (int)data;
var stepStart = DateTime.Now;
Console.WriteLine("{0} Starting {1} on thread {2}...", stepStart, index, Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(15000);
var stepFinish = DateTime.Now;
Console.WriteLine("{0} Finished {1} on thread {2}, duration: {3}",
stepStart, index, Thread.CurrentThread.ManagedThreadId, stepFinish - stepStart);
},
i));
}
Task.WaitAll(tasks.ToArray());
var mainFinish = DateTime.Now;
Console.WriteLine("{0} Finished, duration {1}", DateTime.Now, mainFinish - mainStart);
Console.WriteLine("Press any key to exit.");
Console.Read();
// Output
//5/25/2017 8:03:43 PM Starting 0 on thread 10...
//5/25/2017 8:03:43 PM Starting 1 on thread 11...
//5/25/2017 8:03:43 PM Starting 2 on thread 12...
//5/25/2017 8:03:43 PM Starting 3 on thread 13...
//5/25/2017 8:03:44 PM Starting 4 on thread 14...
//5/25/2017 8:03:45 PM Starting 5 on thread 15...
//5/25/2017 8:03:46 PM Starting 6 on thread 16...
//5/25/2017 8:03:47 PM Starting 7 on thread 17...
//5/25/2017 8:03:48 PM Starting 8 on thread 18...
//5/25/2017 8:03:49 PM Starting 9 on thread 19...
//5/25/2017 8:03:43 PM Finished 0 on thread 10, duration: 00:00:15.0018957
//5/25/2017 8:03:43 PM Finished 1 on thread 11, duration: 00:00:15.0175209
//5/25/2017 8:03:43 PM Finished 2 on thread 12, duration: 00:00:15.0175209
//5/25/2017 8:03:43 PM Finished 3 on thread 13, duration: 00:00:15.0165291
//5/25/2017 8:03:44 PM Finished 4 on thread 14, duration: 00:00:15.0156567
//5/25/2017 8:03:45 PM Finished 5 on thread 15, duration: 00:00:15.0156012
//5/25/2017 8:03:46 PM Finished 6 on thread 16, duration: 00:00:15.0155997
//5/25/2017 8:03:47 PM Finished 7 on thread 17, duration: 00:00:15.0155989
//5/25/2017 8:03:48 PM Finished 8 on thread 18, duration: 00:00:15.0155985
//5/25/2017 8:03:49 PM Finished 9 on thread 19, duration: 00:00:15.0156328
//5/25/2017 8:04:04 PM Finished, duration 00:00:21.0322775
//Press any key to exit.
}