jQuery Ajax calls to web service seem to be synchronous

纵饮孤独 提交于 2019-12-27 16:07:13

问题


I have two ajax calls to a web service from jquery.

The first call (GetMessages) starts an interval in javascript (setInterval) and returns a string array of messages stored in a session variable.

The second call (UploadUsers) uploads users and saves the status in the session to be returned in the method GetMessages. So UploadUsers adds messages to the Session and GetMessages retrieves the messages and displays them for the client.

The problem is even though I call both methods asynchronously, GetMessages waits until UploadUsers is finished. It just loads.

I even put a thread.sleep between each user being added and I expect to have GetMessages return "1/10 users have been added", "2/10 users have been added", each on separate calls.

What happens is GetMessages doesn't return anything until UploadUsers is finished and then brings all the text at once.

I have a lot of code so I don't know what to put but here it goes:

UploadUsers.aspx

callAsynchMethod('ClientStatusHandler.asmx/GetMessages',
'', printMessages, stopPollingError);

callAsynchMethod('ClientStatusHandler.asmx/StartRetrievingLeads',
data, stopPolling, stopPollingError);

Site.js

function callAsynchMethod(url, keyValue, callBack, callBackError) {
    $.ajax({
        type: "POST",
        url: url,
        data: keyValue,
        contentType: "application/json; charset=utf-8",
        success: callBack,
        error:callBackError
    });
}

ClientStatusHandler.asmx.cs

const string key = "LUMessages";
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        [WebMethod(EnableSession = true)]
        public string[] GetMessages()
        {

            if (Session[key] != null)
            {
                string[] messages = ((IList<string>)Session[key]).ToArray();
                ((IList<string>)Session[key]).Clear();
                return messages;
            }
            return new string[] { };
        }







  [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
     [WebMethod(EnableSession = true)]
      public string[] UploadUsers()
     {
    //This function adds a user and calls SaveMessageToQueue 
//for every user.
    //I see the message being entered into the session and 
//I call Thread.Sleep(10000) 
    //between messages.
    }









     private void SaveMessageToQueue(string m)
        {

        IList<string> messageQueue = (List<string>)HttpContext.Current.
Session["LUMessages"];
        messageQueue.Add(m);
         }

回答1:


This is because you have enable the Session and the Session lock all the calls until they return.

You can read also this question: Replacing ASP.Net's session entirely

also read: https://stackoverflow.com/a/3660837/159270



来源:https://stackoverflow.com/questions/9052401/jquery-ajax-calls-to-web-service-seem-to-be-synchronous

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