c# - 异步网络方法

标签 c# .net asmx

我有一个客户/服务。

该服务有一个方法需要很长时间才能完成(它与数据库交互)。

我通过从页面到客户端的 AJAX 请求调用此方法,然后再到服务并返回。

我的服务代码:

[WebMethod]
public static string LookupUPC(string sessionId, string upc) {
    string response = "";
    var client = new SmartShopService.SmartShopInterfaceClient();
    try {
        response = client.LookupUPC(sessionId, upc);
    }
    catch (Exception e) {
        throw e;
    }
    finally {
        if (client.State == System.ServiceModel.CommunicationState.Faulted)
            client.Abort();
        else
            client.Close();
    }
    return response;
}

它由 AJAX 请求从页面调用

for(var i = 0;i<10; i++){
$.ajax({
    type: "POST",
    url: "SmartShopGUI.aspx/LookupUPC",
    contentType: "application/json; charset=utf-8",
    data: DataCreator(allData),
    dataType: "json",
    success: function (result) {
        $(upcName).html(result.d);      
    },
    error: AjaxFailed
});
}

现在,这是在页面上异步完成的,但客户端正在同步发送请求。我想更改它,以便如果它同时请求 10 个请求,它会向服务发送 10 个不同的请求。

http://www.screencast-o-matic.com/watch/cX1Qo8qV2

这是一个可能有帮助的视频。

最佳答案

去掉webmethod中对Session的依赖,你可能会发现session访问是串行的,这就是block。

http://msdn.microsoft.com/en-us/library/ms178581.aspx

Concurrent Requests and Session State

Access to ASP.NET session state is exclusive per session, which means that if two different users make concurrent requests, access to each separate session is granted concurrently. However, if two concurrent requests are made for the same session (by using the same SessionID value), the first request gets exclusive access to the session information. The second request executes only after the first request is finished. (The second session can also get access if the exclusive lock on the information is freed because the first request exceeds the lock time-out.) If the EnableSessionState value in the @ Page directive is set to ReadOnly, a request for the read-only session information does not result in an exclusive lock on the session data. However, read-only requests for session data might still have to wait for a lock set by a read-write request for session data to clear.

关于c# - 异步网络方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6294483/

相关文章:

json - 如何将 jqGrid 与 asmx webservice C# 绑定(bind)

c# - 计划每小时运行一个宏

c# - 如何避免 OrderBy - 内存使用问题

c# - 使用 Parallel.ForEach<T> 设置 Parallel.ForEach 外部的 bool 值

java - 使用 httpurlconnection 发布到 Web 服务

winforms - 我可以更改配置文件中的 Web 服务引用 URL 吗?

c# - 异步下载时设置用户状态

c# - 如何根据对象类型动态调用函数

.net - 为什么我的 clickonce 应用程序不生成 HTML 文件?

c# - 与 TPT 代码优先 Entity Framework 中的引用约束冲突