Jason King Team : Web Development Tags : Technology Web Development Tips & Tricks

Slow web services? Use .NET 4.5 async and ajax to trick the user into believing they’re fast

Jason King Team : Web Development Tags : Technology Web Development Tips & Tricks

Recently I was working on a web page which gathered information from a user as part of a wizard form.   On the first step the user would enter a card number and 4 other fields in order to proceed.   The user details were validated against data retrieved from external web services.   6 web service calls were required before the user could proceed to the next step.   Each web service call would take about 3 seconds to return.   So the average user would have to wait 18 seconds before they could continue.   Not acceptable for most people.

Luckily with new features in .NET 4.5 the performance can quite easily be improved.   The first 2 web service calls had to be made synchronously but it didn’t matter which order the last 4 were called.   By updating the code, the last 4 web services can be called asynchronously taking a total of 3 seconds rather than 12.  

Visual Studio 2012 can generate the asynchronous web services calls for you.   Just right click on your service reference and choose the “Configure Service Reference” option.

Visual Studio Asynchronous Web Services Calls

Now when you call the async web service method, a Task will be returned rather than just the response from the web service.   Use the await keyword to wait for the web service call to finish.

Await for the Web Service

The following code waits for all web service calls to complete:

When all Web Services complete

To further improve the performance I’ve started to fetch the data from the web services as soon as the user blurs from the first field (which fortunately is the only field required by the web services).   A simple ajax call to the server will retrieve the data from the web services and store in session as the user is completing the other fields.   Now when the user clicks continue, all the data has been fetched and can be very quickly retrieved from session.   The bottom line is that the average user has a 1 second delay rather than 18.