Search code examples
asp.netmultithreadingasync-awaitthreadpoolapplication-pool

Calling Thread.Run in an ASP.Net application running on IIS


Consider the following code which runs in an ASP.Net web application on IIS...

_thread = new Thread(Method1)
_thread.Start();

As there is a thread pool within the ASP.Net process what is the effect of this code? Specifically...

  1. Will it take another thread from the ASP.Net thread pool? Or from a different threadpool? Or does this code bypass the thread pool and just get a new thread?

  2. Is this the same thread pool that is used to serve page requests? Therefore, this code which was put in to improve performance could actually reduce it by taking another thread that could be used to serve another resource to another user?

  3. Is the thread pool only used for serving non-static resources? Does IIS have it's own thread pool for serving resources that do not run through the managed pipeline?

  4. What would happen if the App. Pool was recycled after calling _thread.Start()? Would IIS allow this thread to complete before closing down the application pool?

  5. It seems to be that this code forces the creation of a new thread. Would there be a benefit to swapping this code to use Async/Wait? The code that runs in Method1() is IO bound.


Solution

    1. When you call new Thread explicitly, that thread is not part of the thread pool. You are fully on your own.

    2. The so called ASP.NET thread pool is purely used to process request messages (to host HttpApplication derived objects).

    3. Static files are served by IIS natively, so the ASP.NET thread pool is for ASP.NET contents only. But here you should notice all happens inside the worker process (w3wp.exe). Just some are processed by native components, while others are by managed components. The pipeline is unified if you are using the integrated pipeline mode.

    4. Application pool recycle only waits for requests to be processed. Your own threads will be killed when all requests are done.

    5. Async/await does not create threads automatically. But by switching to async/await, you do avoid create a thread, and that should help improve performance.