I have a Web API Controller with the following method inside:
public string Tester()
{
Thread.Sleep(2000);
return "OK";
}
When I call it 10 times (Using Fiddler), I expect all 10 calls to return after ~ 2 seconds. However the calls return after 2,4,8...20 seconds, respectively. What is blocking it from running concurrently? How do I fix that?
Do regular Controllers behave the same as web-api controllers?
I don't think I'm answering your question but what I'd like to write here is too big for a comment.
First up, ASP.NET Web API has nothing to do with session state. In fact, if session has to be used with web API, then it needs to be explicitly enabled.
Now, I have the same exact API controller like you and I host it in IIS. If I make concurrent requests, it is running the requests in parallel and not serially. Here is how I tested from Fiddler.
First, I made a GET to the API and waited for 200 status code (#1 in Fiddler left pane). Then, I selected #1 and pressed U to replay the same request unconditionally 9 times. With that I have 10 requests in the left pane (#1 through #10). Then, I selected all 10 of them and pressed R to reissue all the ten requests in parallel. I then selected requests 11 through 20 in the left pane and went to Timeline tab. I see this graph.
PS. I tested the web API running locally, BTW.
Next, I wanted to log the time stamp request as received by the action method. So, I modified action method to return a string like this.
I got the following.
To me this means, all the requests are running in parallel.
What you describe matches the default behavior of the ASP.NET Session State and can be solved by disabling it in web.config.
Source: ASP.NET Session State Overview
Try use this instead:
See this to know the difference between Task.Delay vs Thread.Sleep which blocks http://social.technet.microsoft.com/wiki/contents/articles/21177.visual-c-thread-sleep-vs-task-delay.aspx
Look at this question, which is relative to your problem: Are all the web requests executed in parallel and handled asynchronously?
It states that:
To solve this, you can use async methods, as described here.
Generally, you need to declare your method as async, like this:
You must have enabled the
Session State
somewhere for Web Api. Web API is restful by default and has no session. Check your global.asax Application_AuthenticateRequest section (this is where I enable session state for Web Api). Find where you enabled your session state at and set it to read-only mode to allow for parallelism on web methods using session state. See this question which is similar: Web API Service - How to make the requests at the server to be executed concurrentlyLook for something like this:
Change it to this: