Why sometimes Task is significantly slower than Thread?

╄→гoц情女王★ 提交于 2020-12-29 19:38:32

问题


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

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

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

My system configurations:

  • Visual Studio 2010 SP1
  • .NET Framework 4.0
  • Windows 7 64bit.
  • 4GB RAM
  • AMD Phenom II 635 (4 core, 2.9 GHz)

Any ideas? Thanks.

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


回答1:


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.

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.

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



来源:https://stackoverflow.com/questions/6637932/why-sometimes-task-is-significantly-slower-than-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!