Why so much difference in performance between Thread and Task?

c#, multithreading

Solution

The two are not the same.

When you use `Task.Factory.StartNew`, you're scheduling a task to run on the `ThreadPool`. When you make a new `Thread`, you're having to create and start a new thread.

In the first case, the threads are already created and reused. This causes the overhead of scheduling the tasks to be far lower, as the threads don't have to be created each iteration.

Note that the behavior is not the same, however. When creating a separate thread, each task is getting it's own thread. They will all get started right away. When using `Task.Factory.StartNew`, they're put into the scheduler to run on the `ThreadPool`, which will (potentially) limit the number of concurrent threads started. This is usually a good thing, as it prevents overthreading from occurring.

Problem

Windows 7, Intel CORE i3, 64 bit, RAM 4Gb, 2.27 GHz .NET Framework 4.0 I have the following code: ``` static void Main(string[] args) { var timer = new Stopwatch(); timer.Start(); for (int i = 0; i < 0xFFF; ++i) { // I use one of the following line at time Task.Factory.StartNew(() => { }); new Thread(() => { }).Start(); } timer.Stop(); Console.WriteLine(timer.Elapsed.TotalSeconds); Console.ReadLine(); } ``` If I use Task the output is always less then 0.01 seconds, but if I use Thread the output is always greater than 40 seconds! How is it possible? Why so much difference?

Original source