Thread vs ThreadPool

后端 未结 11 2204
鱼传尺愫
鱼传尺愫 2020-11-22 15:57

What is the difference between using a new thread and using a thread from the thread pool? What performance benefits are there and why should I consider using a thread from

相关标签:
11条回答
  • 2020-11-22 16:24

    I was curios about the relative resource usage for these and and ran a benchmark on my 2012 dual-core Intel i5 laptop using .net 4.0 release build on windows 8. Thread Pools took on average 0.035ms to start where Threads took an average of 5.06ms. In other words Thread in the pool started about 300x faster for large numbers of short lived threads. At least in the tested range (100-2000) threads, the total time per thread seemed pretty constant.

    This is the code that was benchmarked:

        for (int i = 0; i < ThreadCount; i++) {
            Task.Run(() => { });
        }
    
        for (int i = 0; i < ThreadCount; i++) {
            var t = new Thread(() => { });
            t.Start();
        }
    

    0 讨论(0)
  • 2020-11-22 16:25

    If you need a lot of threads, you probably want to use a ThreadPool. They re-use threads saving you the overhead of thread creation.

    If you just need one thread to get something done, Thread is probably easiest.

    0 讨论(0)
  • 2020-11-22 16:32

    Thread local storage is not a good idea with thread pools. It gives threads an "identity"; not all threads are equal anymore. Now thread pools are especially useful if you just need a bunch of identical threads, ready to do your work without creation overhead.

    0 讨论(0)
  • Check here for an earlier thread:

    When should I not use the ThreadPool in .Net?

    Summary is that Threadpool is good if you need to spawn many shortlived threads, whereas using Threads gives you a bit more control.

    0 讨论(0)
  • 2020-11-22 16:33

    Thread:

    1. Creating a Thread is far slower than using Thread-pool.
    2. You can change the priority of a thread.
    3. The max number of threads in a process related to resources.
    4. Thread is at the OS level and controlled by OS.
    5. Using Thread is a better option when the task is relatively long-running

    Thread-Pool:

    1. Running a Thread on thread-pool is far faster than directly creating a Thread.
    2. You can not change the priority of a thread run based on Thread-pool.
    3. There is only one Thread-pool per process.
    4. The Thread-pool is managed by CLR.
    5. The Thread-pool is useful for short-lived operation.
    6. The numbers of Threads in Thread-pool is related to the application load.
    7. TPL tasks run based on Thread-pool
    0 讨论(0)
  • 2020-11-22 16:38

    also

    new Thread().Start()

    spawns Foreground thread that will not die if you close your program. ThreadPool threads are background threads that die when you close the app.

    0 讨论(0)
提交回复
热议问题