Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
120 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...