Why are my requests to web.api being blocked by long running controller code?

情到浓时终转凉″ 提交于 2019-12-13 17:20:50

问题


I'm working on my local development environment using angular to issue ajax calls to Web.API (IIS 8.5 hosted). I'm making 5 calls via different angular controllers simultaneously, each of which look like this:

$scope.medications = API.Client.MedicationProfiles.query({ clientId: clientId });

The API service has this definition for the Client.MedicationProfiles resource:

this.Client.MedicationProfiles = $resource(
    '/Noteable.API/api/Client/:clientId/MedicationProfiles/:id',
    {
        clientId: '@clientId',
        id: '@Id'
    },
    {
        update: { method: 'PUT' }
    }
);

I can see all of the requests going to the server basically at once using the chrome dev tools as the page loads but it appeared that they were coming back one at a time as if they had been run synchronously. I put a thread.sleep in one of the Web.API controller actions and sure enough, all calls issued after that one fail to return until the sleeping one does. This doesn't make any sense to me and I'm wondering if someone can tell me in what case they would expect this.


回答1:


This may be a good situation to implement an asynchronous pattern on your web api backend - you'll be alleviated from your ajax calls blocking once they hit your controller. This can be achieved by leveraging an async and await pattern. You'll want to return a Task, which represents an asynchronous operation.

An example may include...

public async Task<IHttpActionResult> Put(string clientId)
{
    var response = await this.yourService.yourSavingMethod(clientId);

    return Ok(response);
}

Also see SO question Why is this web api controller not concurrent? for more details and insight on the issue. Furthermore, the default behavior for ASP.NET Session State and can be changed to accommodate concurrent requests. An example may include

HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.ReadOnly)

ASP.NET Session State Overview




回答2:


I think your problem is caused either by browser or ASP.NET. In case it's ASP.NET, take a look at this thread:

C# Web API - Blocking

In case it's your browser, take a look at this thread with example code:

Why is my async ASP.NET Web API controller blocking the main thread?



来源:https://stackoverflow.com/questions/30057531/why-are-my-requests-to-web-api-being-blocked-by-long-running-controller-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!