问题描述
我阅读了大量的.Net资源的告诉我,我应该使用一个线程池线程,而不是实例化一个新的线程自己。他们说你应该这样做,因为实例化一个新的线程是一个昂贵的操作。创建线程,使得它非常昂贵的操作过程中,会发生什么?
I read lots of .Net resources telling me that I should be using a thread pool thread rather than instantiating a new thread myself. They say you should do this because instantiating a new thread is an expensive operation. What happens during thread creation that makes it an expensive operation?
推荐答案
一切都是相对的。创建一个新的线程是昂贵的......相对于没有创造之一。如果你没有做大量的每个线程的工作,这项工作涉及建筑拆了线可能会弥补你的CPU时间衡量的部分。但它相对于创建一个新的进程,特别是在Windows便宜。
Everything is relative. Creating a new thread is expensive... relative to not creating one. If you're not doing a lot of work per thread, the work involved in building and tearing down the threads can potentially make up a measurable portion of your cpu time. But it's cheap relative to creating a new process, especially on Windows.
这也是通常最好使用线程池,因为它被调整来帮助你避免一次激活太多线程。你很少需要超过少数活动的线程在同一时间,否则你会花大量的CPU时间执行它们之间的上下文切换。使用线程池管理这个给你,作为额外的请求被排队,直到一个工作线程已准备就绪。
It's also generally better to use the threadpool because it is tuned to help you avoid having too many threads active at once. You rarely want more than a handful of threads active at one time, or you'll spend a lot of cpu time performing context-switches between them all. Using the threadpool manages this for you, as additional requests are queued until a worker thread is ready.
这篇关于为什么创建一个新的线程昂贵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!