Home .NET Asynchronous programming in ASP.NETMVC 4 applications

Asynchronous programming in ASP.NETMVC 4 applications

by admin

After reading article about learning MVC and seeing commentary user RouR I was very interested in the topic, and on the fly I decided to translate the original article
If you, too, dear hubrajitel, are interested, please kat!
"I will try to show you what is new in C# 5.0 in terms of asynchronous programming when using the keyword await . Especially for ASP.NETMVC 4 web applications."
I’ve been playing around for a while with Visual Studio Async CTP and now I have enough ideas about how it works and how to use it intelligently. And that means I can write about it.
The main problem with most of our software is operations that take a long time to execute. The user starts such an operation and it blocks the main thread of the program until its execution is finished. And as a result we get user-uncomfortable software and unsatisfied clients. I’m sure each of us has encountered such programs!
Asynchronous programming is far from a new paradigm, it was already there in the days of .NET1.0. I wasn’t very interested in programming 3 years ago, so the concept is still fairly new to me. As far as I’ve read, the concept has evolved largely from a .NET perspective to asynchronous programming and I think is now at its best stage.
On the one hand, it’s very easy to get confused about asynchronous programming as it has happened to me several times already. I’ve gone back and forth and thought a lot about how this thing works and where to apply it. And I’d like to believe I got it right in the end. On the other hand, it’s even easier to get confused about asynchronous programming if we apply it to web applications, because we don’t have a UI stream to which we can immediately output the results of our work. Asynchronous or not, the user has to wait for some time. This is why asynchronous programming is undesirable for web applications. And if you think so too (and I used to think so myself), then you haven’t figured it out yet!
If your operation is synchronous and takes a long time, then you have no choice but to block the main thread until it completes. And if you are doing the same operation asynchronously, that means that you start the operation and keep doing something, only returning to the results of your operation when it has already finished. Between the start and the end of the operation, your thread is free and can do other things. I think this is where most people get confused. Creating additional threads is an overhead and can lead to problems, but I think that’s a thing of the past. In .NET 4.0 the limit on the number of threads that can run was increased dramatically, but that doesn’t mean that you have to create lots of threads everywhere, at least now you don’t have to worry about creating another thread. There is a lot of discussion (or should I say already passed?) about asynchronous programming :

I don’t know the exact answer to all of these questions, but here are a couple of examples :

  • Windows Runtime (WinRT) is designed with good asynchronous support. Anything that runs longer than 40ms (network related operations, file system related operations – i.e. all basic I/O) all have to be asynchronous!
  • ASP.NET Web API allows you to give your service data in several formats. The only thing to note is that it has almost no synchronous calls. Literally (not figuratively) – just no synchronous calls for some methods!

Now, as they say, it’s about time we took advantage of asynchrony in one way or another. So what’s the problem? And the problem is how this asynchronous model works. As the Anders Heilsberg , this software model turns our code inside out. Not to mention how very difficult it is to make nested calls to asynchronous operations with exception handling.

Visual Studio Async CTP and how it works

In C# 5.0 we will have a new asynchronous programming model, very similar to synchronous programming. In the meantime, the developers have released a CTP for the current version, which is available under a Go-Live license. Here’s a quote from the AsyncCTP specification:
" Asynchronous functions – A new feature in C# that makes it easy to describe asynchronous calls. When function execution reaches an expression with the keyword await and its execution begins, the rest of the function will be rebuilt as an automatic continuation of the operation being executed, and there will be a momentary return from the asynchronous function, while the function itself will continue to execute. In other words, the work of arranging the code execution order is now done by the language itself instead of the programmer. As a result, asynchronous code acquires a logical structure;
Asynchronous function – is a class method or an anonymous function, marked with the modifier async It can return as an object of class Task , and Task<T> for arbitrary type T – in such functions can be await If, on the other hand, the function labeled async , returns void (which is also acceptable) – then use await will fail. But on the other hand, we can, on the other hand, as T to use any type.

ASP.NET MVC 4 and asynchronous C# features

Proper use of asynchrony in ASP.NET MVC applications can have a very positive impact on performance. Believe it or not, it does. I’m going to show you how.
So why aren’t we doing everything asynchronously everywhere? Because it’s very hard, error prone, and ultimately hard to maintain our application afterwards. But with the new asynchronous model, that’s about to change.
Asynchronous programming has changed a lot in ASP.NET MVC 4. You may know that in ASP.NET MVC 3, our controller must be inherited from AsyncController and must conform to a certain pattern. You can read about it in the article " Using asynchronous controllers in ASP.NET MVC ".
In ASP.NET MVC 4 we do not need to use the AsyncController anymore, we just need to mark our controller with the keyword async and return an object of class Task or Task<T> (where T – usually ActionResult ).
I tried to combine two examples in the same application that do the same action, synchronously and asynchronously, respectively. I also did load testing and the results shocked me! Now let’s take a look at the code.
First, I created a simple REST service, using the new ASP.NET Web API The simplest model, which stores the collection in memory (you could have used the database instead):

public class Car{public stringMake;public string Model;public int Year;public int Doors;public string Colour;public float Price;public int Mileage;}public class CarService{public List<Car> GetCars(){List<Car> Cars = new List<Car>{new Car{Make="Audi", Model="A4", Year=1995, Doors=4, Colour="Red", Price=2995f, Mileage=122458}, new Car{Make="Ford", Model="Focus", Year=2002, Doors=5, Colour="Black", Price=3250f, Mileage=68500}, new Car{Make="BMW", Model="5 Series", Year=2006, Doors=4, Colour="Grey", Price=24950f, Mileage=19500}//This keeps going like that};return Cars;}}

And the service code :

public class CarsController :ApiController{public IEnumerable<Car> Get(){var service = new CarService();return service.GetCars();}}

So, I have a service. Now I will write a web application which will get the data from the service and display it. To do this I wrote a service class which gets the data and deserializes it : for asynchronous calls I used a new HttpClient and for synchronous calls I used the usual WebClient I also used Json.NET :

public class CarRESTService{readonly string uri = "http://localhost:2236/api/cars";public List<Car> GetCars(){using (WebClient webClient = new WebClient()){return JsonConvert.DeserializeObject<List<Car> >(webClient.DownloadString(uri));}}public asyncTask<List<Car> > GetCarsAsync(){using (HttpClient httpClient = new HttpClient()){return JsonConvert.DeserializeObject<List<Car> >(awaithttpClient.GetStringAsync(uri));}}}

About the method GetCars has nothing to say – it’s simple. But about GetCarsAsync we can say the following :

  • It is tagged with the keyword async which tells us that there is some asynchronous code here.
  • We used the keyword await before HttpClient.GetStringAsync which returns Task<string> And we can use it as a normal string – keyword await allows us to.

And finally, here is the controller :

public class HomeController : Controller{private CarRESTService service = new CarRESTService();public async Task<ActionResult>Index(){return View("index", await service.GetCarsAsync());}public ActionResult IndexSync(){return View("index", service.GetCars());}}

So we have Index – asynchronous function returning Task<ActionResult> , and IndexSync – is a normal synchronous call. If we go to /home/index or /home/indexsync we will not see much difference in the opening speed of the pages, it is about the same.
To measure the difference in the performance of these methods, I created load tests in MS Visual Studio 2010 Ultimate. I will open these two pages for two minutes, starting with a load of 50 users, gradually increasing it by 20 users every 5 seconds. The maximum limit will be a value of 500 users. See the result (clickable):
Asynchronous programming in ASP.NETMVC 4 applications

We see that for the synchronous version the response time is 11.2 seconds, and for the asynchronous 3.65 seconds. I think the difference is obvious.
This is where I became committed to the concept of "Anything that runs longer than 40ms (network related operations, file system related operations – i.e. all basic I/O) – it should all be asynchronous!"

You may also like