Calling Asyncronous Method Inside a Loop
What will happen when you call an Asyncronous method inside a loop? I did a small experiment to find the answer. The first thing is to register the asyncronous method. I chose to go with ASP.NET 2.0 Client Callbacks.
protected
void Page_Load(
object sender,
EventArgs e)
{
string cbScript = ClientScript.GetCallbackEventReference(this, "arg", "RecieveServerData", "context",true);
string script = String.Empty;
if (!ClientScript.IsClientScriptBlockRegistered("CallServer"))
{
script = "function CallServer(arg,context) { " + cbScript + "}";
ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", script, true);
}
}
And here is the JavaScript code:
<
script language="javascript" type="text/javascript"> function
RecieveServerData(rValue)
{
var request = this.xmlRequest;
alert(request.status);
}
function
MakeAsyncCall()
{
CallServer('','');
CallServer('','');
CallServer('','');
}
</
script> If the above code resulted in "__pendingCallbacks[...].async is null or not an object" error then check out this post.
Anyway, the above code will not freezes up the computer. But if you run the above code in a loop the application will blow up.
// The following code will crash the application
// for(i=0;i<=3;i++)
// {
// // Make an asyncronous request
// CallServer('','');
// }
The reason is that the new thread will call the function again which will cause more and more threads to be created. This process will continue on until the application fails to connect to the server.
So, if there is some work that you need to perform which needs iteration and calling Asyn method. Then it is better to group all those request in a single object and send that object to the server. Later on the server you can filter or split the requests as needed.