为什么有时 Task 比 Thread 慢得多? [英] Why sometimes Task is significantly slower than Thread?

查看:75
本文介绍了为什么有时 Task 比 Thread 慢得多?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 MVVM 模式制作 WPF 应用程序.我发现有时 Task 比 Thread 慢得多.例如,在测试 ViewModel 中:

I'm making a WPF application using MVVM pattern. I found sometimes Task is significantly slower than Thread. For example, in a test ViewModel:

public void DoSomething()
{
    Stopwatch stopwatch = Stopwatch.StartNew();
    new Thread(() =>
        {
            Debug.Print(string.Format("Elapsed: {0}", stopwatch.ElapsedMilliseconds));
        }).Start();
}

输出通常是Elapsed: 0.它花费0毫秒.但是如果我用 Task 替换 Thread.可能需要 5000~15000 毫秒.

The output usually is Elapsed: 0. It cost 0 millisecond. But if I replace Thread with Task. It could cost 5000~15000 milliseconds.

我试图在另一个 WPF 项目中重现这个,但失败了.

I tried to reproduce this in another WPF project, but failed.

我的系统配置:

  • Visual Studio 2010 SP1
  • .NET 框架 4.0
  • Windows 7 64 位.
  • 4GB 内存
  • AMD Phenom II 635(4 核,2.9 GHz)

有什么想法吗?谢谢.

(抱歉,我无法上传有此问题的项目)

(Sorry, I can't upload the project that has this issue)

推荐答案

默认情况下,Task 不会创建新线程,而是在线程池中排队.这意味着当所有线程池线程都忙时,任务可能会等待(在极端情况下无限长),直到它真正开始执行.

By default, Task doesn't create a new thread, but enqueues on the thread pool. That means when all of the thread pool threads are busy, the task might wait (in extreme cases infinitely long), until it actually starts executing.

线程池尝试确定最佳线程数,并且每个内核至少创建一个线程.您可以使用 ThreadPool.SetMinThreads() 以提高使用的最少线程数,但要小心,它可能会降低性能.

The thread pool tries to determine the optimal number of threads and it creates at least one thread per core. You can use the ThreadPool.SetMinThreads() to raise the minimal number of threads used, but be careful with this, it may decrease the performance.

另一种选择是创建您自己的TaskScheduler 完全按照您想要的方式使用线程.

Another option would be to create your own TaskScheduler that uses threads exactly the way you want.

这篇关于为什么有时 Task 比 Thread 慢得多?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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