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);
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…