问题
In this web tutorial on threading in C#, Joseph Albahari writes: "Don't go sleeping in pooled threads!" Why should you not do this? How badly can it affect performance? (It's not that I want to do it; I'm just curious.)
回答1:
Thread is a heavy-weight object.
Creating a new thread requires lots of resources, such as assigning 1 MB for a managed stack, creating managed thread object, kernel stack, kernel thread object, user thread environment block. This all takes time and memory. Therefore you do not want to create and destroy objects really quickly. Furthermore, once you have more than one thread context switching will take some resources as well
Thread pool is a place where CLR can put unused threads, in case your application needs it.
Threadpool initially contains 0 threads, once you request a thread from a pool, the pool will quickly create the minimum number of threads defined for the pool. After around 2 minutes unused threads get killed. But if the load increases and you need more threads, thread pool will slowly create new threads until the maximum bound reached. You cannot have more threads than maximum, all new requests will be queued and executed once a working thread returned to the pool. In worse case scenario you can get OutOfMemoryException
If a thread taken from a pool is blocked, it:
- Holds the resources
- Does not do any valuable work, while an application may need this thread for a new request
- Breaks scalability by introducing blocks
回答2:
There are only a limited number of threads in the thread pool; thread pools are designed to efficiently execute a large number of short tasks. They rely on each task finishing quickly, so that the thread can return to the pool and be used for the next task.
So sleeping in a thread pool thread starves out the pool, which may eventually run out of available threads, and be unable to process the tasks you assign to it.
回答3:
The thread pool is meant to quickly do a relatively short task on a different thread without having to spend the cost of creating a new thread. The thread pool has a maximum number of threads, and once that is reached, tasks are queued until a thread becomes available.
A thread sleeping on the thread pool would therefore hold up the queue, or contribute to thread pool exhaustion.
来源:https://stackoverflow.com/questions/6305814/sleeping-in-a-pooled-c-sharp-thread