为什么长时间运行的控制器代码会阻止我对web.api的请求? [英] Why are my requests to web.api being blocked by long running controller code?

查看:70
本文介绍了为什么长时间运行的控制器代码会阻止我对web.api的请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用angular来对Web.API(托管IIS 8.5)发出ajax调用,在我的本地开发环境中工作.我同时通过不同的角度控制器进行了5次通话,每个通话都像这样:

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 });

API服务对Client.MedicationProfiles资源具有以下定义:

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' }
    }
);

当页面加载时,我可以看到所有使用chrome dev工具基本上一次发送到服务器的请求,但是看起来它们一次又一次返回,就好像它们是同步运行的一样.我在Web.API控制器操作之一中放入了一个thread.sleep,很确定,在此之后发出的所有调用都无法返回,直到休眠的才返回.这对我来说没有任何意义,我想知道是否有人可以告诉我在什么情况下会发生这种情况.

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.

推荐答案

在Web api后端上实现异步模式可能是一个好情况-一旦ajax调用击中了控制器,您将得到缓解.这可以通过利用 async 来实现>和 await 模式.您将要返回 Task ,表示异步操作.

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);
}

另请参阅问题为什么此Web api控制器不并发?有关此问题的更多详细信息和见解.此外,ASP.NET会话状态的默认行为可以更改以适应并发请求.一个例子可能包括

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会话状态概述

这篇关于为什么长时间运行的控制器代码会阻止我对web.api的请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆