Reputation: 2042
When a HTTP request is received by IIS, it hands off the request to the requested application in an application pool that is serviced by one or more worker processes. A worker process will spawn a thread from the shared thread pool (if required) to service the http request.
(i) In the context of a web api controller, when this request is received, is the controller instantiated and assigned to the spawned thread?
(ii) When there are multiple http requests to the same api controller, will there be as many instances of the controller per spawned thread?
(iii) In a scenario where a resource that is not thread safe (dbContext) is declared at the class level and instantiated in a constructor and then used in the class methods. Will there be issues committing and managing transactions?
In essence, is there a one-to-one match of controller instance per thread? (I am aware that with asp.net multiple threads can actually service a single http request).
Upvotes: 10
Views: 8627
Reputation: 62300
(i) In the context of a web api controller, when this request is received, is the controller instantiated and assigned to the spawned thread? (ii) When there are multiple http requests to the same api controller, will there be as many instances of the controller per spawned thread?
When a request is received, a controller instance is created by ControllerFactory or DependencyResolver.
Basically, main thread creates an controller instance, and then the same instance is shared between multiple threads until the request is completed.
(iii) In a scenario where a resource that is not thread safe (dbContext) is declared at the class level and instantiated in a constructor and then used in the class methods. Will there be issues committing and managing transactions?
Yes, share member or static are not thread safe. However, local variables inside action methods are thread safe.
Upvotes: 4
Reputation: 614
Answer to your questions by point:
(i). Yes
(ii). No. Normally controllers are singleton and not thread safe. You create multiple threads to handle multiple request but they cal same controller instance (or service)
(iii). Yes. Its your responsibility to look after data sanity checks or thread safety concerns. If you don't then you can face all sort of issues like dirty read, dirty ride, thread safety... all kind of thread safety issues.
You can treat controller as service so just delegate the incoming requests to new sub-services or controllers by creating new instance like creating a new task handler for each request BUT you still need to think about thread safety of shared resources like Database.
Upvotes: 0