Async Web Api Basics

Recently on my project we were doing some performance testing and found something that really made me take note.  The load performance of Web Api is greatly increased by using Async services.  I was reading about this, and using Async services, allows the server to scale better by the way the thread is handled by the thread pool.  Great article on the matter is found here, https://msdn.microsoft.com/en-us/magazine/dn802603.aspx

I want to show you the basics of exposing and supporting async web api services.

First, here is an example that you get with Web Api.  I changed the response to be IHttpActionResult, you should always use that as a response type for Web Api.  Also, I changed one of the methods to call a service, that in turn calls a socket to send and receive data.

Starting Synchronous Service:

 

Here is the SocketService as sync

 

Converting these exposed services to async is usually pretty easy, but one thing you need to remember with using async and await is that once you start down that path, you need to normally go all the way through to your external data source to get those performance gains.  First let me change all services to async:

 

That is a start.  I’m going to just focus on the Get from Socket Service method from now on,  where we need to build the async trail down to where the I/O is being performed, in our case a socket call.  I need to update the Socket Service to pass on the async’ness to the socket connections, such as:

This was a little more challenging, since I am now working with the underlying stream more directly, but you can see I now have awaits on the connect, send, and receive.  Finally, I have changed my method signature to first have async, which is required whenever you have await in your method, but to return a Task of string.  This lets the caller know that I can be called async and the task will notify when its compete, with the expected response type.  I just have one slight modification needed for the Get in the controller now:

That await does all the work for you.  It tells me where the async trail leads, meaning, if I want to see what exactly is async I follow this method call.  It also converts the response of that method from a Task to the response type that I originally wanted, which was a string.  This is easier code to write and read as well, no casting, no working with Tasks directly, simple!

Hopefully, you can see from this simple example, what is needed to convert from synchronous services to async services and get on the bandwagon like I have.

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *