Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web Api Controller and Thread Pool

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).

like image 611
Oladipo Olasemo Avatar asked Jun 10 '16 12:06

Oladipo Olasemo


People also ask

What are controllers in Web API?

Controllers in a web API are classes that derive from ControllerBase. This article shows how to use controllers for handling web API requests.

Can I use MVC controller as Web API?

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.

What is the use of ThreadPool QueueUserWorkItem method in C#?

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.

Is thread pool per process?

There is only one thread pool per process.


1 Answers

(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.

like image 79
Win Avatar answered Oct 13 '22 10:10

Win