Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

c# - Why so much difference in performance between Thread and Task?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...