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).
Controllers in a web API are classes that derive from ControllerBase. This article shows how to use controllers for handling web API requests.
In order to add a Web API Controller you will need to Right Click the Controllers folder in the Solution Explorer and click on Add and then Controller. Now from the Add Scaffold window, choose the Web API 2 Controller – Empty option as shown below. Then give it a suitable name and click OK.
QueueUserWorkItem(WaitCallback, Object) Queues a method for execution, and specifies an object containing data to be used by the method. The method executes when a thread pool thread becomes available.
There is only one thread pool per process.
(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With