This MSDN example for an Asynchronous Handler starts the new thread using ThreadPool.QueueUserWorkItem.
I thought that you should not use ThreadPool.QueueUserWorkItem to start the new thread as开发者_如何学编程 the thread is taken from the ASP.net thread pool and defeats the purpose of using an Asynchronous handler.
Is the example wrong?
There are a few things wrong with your assertions:
- When you use
ThreadPool.QueueUserWorkItem
you don't start a new thread. That's the point of having the ThreadPool in the first place. You're reusing a thread from a pool. - You're implying that the example was specifically targeting ASP.NET, when it's not. It's showing you how to use the ThreadPool to fire off background tasks without manually creating new threads (which is costly). The job of determining when and when not to use the ThreadPool is still yours.
- Using the ThreadPool to run an asynchronous task does not "defeat the purpose of using an Asynchronous handler". You use asynchronous handlers for a variety of reasons including not blocking the user experience while work is done and to make use of the resources that the machine has available.
- Firing up another thread manually is not going to give you anything more than using the ThreadPool if you're doing a simple background task. If you are, for some reason, concerned that you'll somehow "starve" IIS of threads in which to serve incoming requests with I think you dismiss that concern. Your machine will be brought to its knees with traffic well before your async workers cause you problems.
- Just to be clear, if you are not running an ASP.NET application, your own process will have a pool of it's own:
When a managed application is executed, the runtime offers a pool of threads that will be created the first time the code accesses it. This pool is associated with the physical process where the application is running, an important detail when you are using the functionality available in the .NET infrastructure to run several applications (called application domains) within the same process. If this is the case, one bad application can affect the rest within the same process because they all use the same pool.
You can use the thread pool or retrieve information about it through the class ThreadPool, in the System.Threading namespace. If you take a look at this class, you will see that all the members are static and there is no public constructor. This makes sense, because there's only one pool per process and we cannot create a new one. The purpose of this limitation is to centralize all the asynchronous programming in the same pool, so that we do not have a third-party component that creates a parallel pool that we cannot manage and whose threads are degrading our performance.
So no, the example is not wrong. The example is perfectly fine and highlights exactly that which it intended.
精彩评论