Thread vs ThreadPool

后端 未结 11 2318
鱼传尺愫
鱼传尺愫 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:39

    The .NET managed threadpool: -

    • Sizes itself based on the current workload and available hardware
    • Contains worker threads and completion port threads (which are specifically used to service IO)
    • Is optimised for a large number of relatively short-lived operations

    Other thread pool implementations exist that might be more appropriate for long-running operations.

    Specifically, use a thread pool to prevent your app from creating too many threads. The most important feature of a threadpool is the work queue. That is, once your machine is sufficiently busy, the threadpool will queue up requests rather than immediately spawn more threads.

    So, if you will create a small, bounded number of threads create them yourself. If you cannot determine up-front how many threads might be created (e.g. they're created in response to incoming IO), and their work will be short-lived, use the threadpool. If you don't know how many, but their work will be long-running, there's nothing in the platform to help you - but you might be able to find alternative threadpool implementations that fit.

提交回复
热议问题