为什么线程和任务之间的性能如此大的差别? [英] Why so much difference in performance between Thread and Task?

查看:95
本文介绍了为什么线程和任务之间的性能如此大的差别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的Windows 7,英特尔酷睿i3,64位,4GB内存,2.27 GHz的结果
的.NET Framework 4.0

我有以下代码:

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();
}

如果我使用任务的输出总是小于<强<0.01秒。,但如果我使用线程的输出总是比 40秒!结果
这怎么可能?为什么如此大的差别?

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?

推荐答案

两者是不一样的。

当您使用 Task.Factory.StartNew ,您要安排任务在线程池运行。当你犯了一个新的,你必须创建和启动一个新的线程。

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.

请注意,该行为是不一样的,然而。当创建一个单独的线程,每个任务是越来越它自己的线程。他们都将马上开始。当使用 Task.Factory.StartNew ,他们投入的调度程序上运行线程池,这将(潜在的)限制开始并发线程的数目。这通常是一件好事,因为它可以防止发生overthreading。

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.

这篇关于为什么线程和任务之间的性能如此大的差别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆