oreilly.comSafari Books Online.Conferences.


AddThis Social Bookmark Button

Calling Web Services Asynchronously
Pages: 1, 2, 3

WaitHandle Object Methods

The WaitHandle object has three important methods; WaitOne, WaitAll, and WaitAny. Multiple calls can be made asynchronously to web services from a single parent thread. Here is an example:

// Declare two instances of Web Service
localhost.MyAsyncWebService webServ1 = 
	new localhost.MyAsyncWebService();
localhost.MyAsyncWebService webServ2 = 
	new localhost.MyAsyncWebService();

// Declare two instances of IAsyncResult
IAsyncResult asyncResult1;
IAsyncResult asyncResult2;

// Make  two Asynchronous Calls to Web Service
asyncResult1 = webServ1.BeginCreateXMLFile
	(this.mLangInput, null, null);
asyncResult2 = webServ2.BeginCreateXMLFile
	(this.mLangInput, null, null);

// Call WaitHandle to wait for the web service method to return
WaitHandle wtHandle = asyncResult.AsyncWaitHandle;
// Causes to Wait until both the calls are returned

// Causes to Wait until any of the calls to be returned
// wtHandleAny();

Here, two calls were made asynchronously to web services. The WaitAll() method causes the parent thread to wait for both (All) of the asynchronous calls to return before it can proceed. The WaitAny() method causes it to just wait for any (Any) asynchronous call to return. If only one asynchronous call is made, then WaitOne() is used. For more information on the WaitHandle object, look here at MSDN.

Callback Vs. WaitHandle

The choice of which approach to use is application-driven. If the application needs the results from the web service to be used in the later stages of the thread, then the WaitHandle is the best approach. For example, if the web service queries a database and retrieves a value that needs to be used in the parent process and then displays the result to the user, then WaitHandle should be used. We need the parent thread to stop processing at a certain stage so that we can use the results from the web service to do further computation and display the final results. Most web apps come under this scenario. In all other scenarios, we can use callback. Mostly Windows apps use this approach.


Asynchronous calls to web services will significantly enhance performance because they enable parallel processing of the parent thread and the web service call by using two separate threads. This will be very effective, especially if the web service method takes a long time to process, since it lets the parent thread continue while the web service is doing its own process.

Related Links

Raj Makkapati is a .NET application developer currently working in Charlotte, North Carolina, developing advanced .NET applications for the mortgage industry.

Return to