Welcome to AspAdvice Sign in | Join | Help

AzamSharp

Some day I will know everything I hope that day never comes

Syndication

Tags

Navigation

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.

 

Published Sunday, May 06, 2007 4:48 PM by azamsharp

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# links for 2007-05-07 &raquo; mhinze.com @ Monday, May 07, 2007 11:31 AM

PingBack from http://mhinze.com/links-for-2007-05-07/

links for 2007-05-07 » mhinze.com

Leave a Comment

(required) 
required 
(required) 
Enter the code you see below