开发者

Why sometimes Task is significantly slower than Thread?

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();
    开发者_如何学Pythonnew 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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜