Search code examples
c#asp.net-coreiisasync-awaitthreadpool

IIS worker thread vs web application thread


I'm maintaining an ASP.NET Core web application that needs to repeatedly run some background threads. I know it's not a good design but currently I have to fix its major issues with minimum effort. Now I wonder if I should worry about handling users http requests by web server or not?

Question is simple but I can't find any clear answer for it:

What is the difference between threads that are created in application like this:

Task.Run(() => { // some parallel job })

and worker threads of IIS that handle http requests?

Are they come from the same thread pool or they're reside in separate pools?


Solution

  • According to this it's all one pool: "ASP.NET Core already runs app code on normal Thread Pool threads." In other words, there isn't a separate max for threads serving requests vs. background threads.

    The biggest difference is that IIS is aware of the threads it creates itself for an incoming request. IIS is not aware of any threads you create yourself.

    When an app pool is recycled, or IIS is shut down, it waits until all requests have finished processing - it waits until the threads it creates for each request has finished processing - and then it kills the process. If you create any threads that outlive the request (for example, if you create a background thread and then send the response back to the client) IIS has no idea that thread is still running and could kill the whole process at any time.

    If you don't return a response until all the threads are complete, then you won't have that specific problem.

    The other issue is that you may hit the maximum number of allowable threads. Then all kinds of weird performance issues would happen. But that depends on how many threads you are creating and how many HTTP requests are coming in.