Channels ▼
RSS

.NET

Using Asynchronous Methods in ASP.NET 4.5 and in MVC 4


Asynchronous methods are usually a good option for I/O bound or network-bound operations, that is, operations that have calls with high latency. In these situations, by using asynchronous methods, the thread used to service the ASP.NET request is allowed to respond to other requests while the asynchronous method is waiting for its high latency calls to complete. This way, you can force a more efficient usage of threads in the ASP.NET thread pool and avoid unnecessary growth of the number of threads that the thread pool has to create and maintain. Remember that threads aren't free and they consume resources.

A common situation in which calls with high latency are common is when your action methods perform requests to other Web services. These scenarios are good candidates for their conversion to asynchronous methods with ASP.NET MVC 4 and .NET Framework 4.5.

In fact, my first experience with ASP.NET MVC 4 consisted of making the aforementioned conversion for many of the action methods for an application that was having frequent Web Server requests rejects with the well-known “Server Too Busy” error (HTTP 503) and was appropriate for an upgrade to ASP.NET MVC 4. Long-running action methods that perform many calls with high latency always create problems and the new asynchronous action methods make it easy to optimize the resources they consume. At the same time, it is possible to increase application responsiveness. I must mention that it was possible to do a similar thing with ASP.NET MVC 3, but it required a lot of extra work. With the async and await keywords, the procedure is really simplified and automatically standardized.

A simple example of asynchronous methods in a WPF application

The focus is still on asynchronous methods with ASP.NET MVC 4. However, let me switch to a simple WPF application to show an example of the simplicity of asynchronous methods and then, I will reuse one of the classes with asynchronous methods in an ASP.NET MVC 4 application. This way, you will understand the simplicity of asynchronous methods in many scenarios.

The following listing shows the code for the MathService class (MathService.cs).

namespace WpfAsyncAwaitSample
{
    using System;
    using System.Net;
    using System.Threading.Tasks;

    class MathService
    {
        private static async Task<decimal> GetSubTotalAsync()
        {
            var downloadedString = await new WebClient().DownloadStringTaskAsync(
                                         new Uri("http://www.drdobbs.com"));

            return (decimal)downloadedString[0];
        }

        private static async Task<decimal> GetOtherChargesAsync()
        {
            var downloadedString = 
            await new WebClient().DownloadStringTaskAsync(new Uri("http://www.drdobbs.com"));

            return (decimal)downloadedString[1];
        }

        public static async Task<decimal> GetCalculatedTotalAsync(decimal salesTaxPercentage)
        {
            var subTotal = await GetSubTotalAsync();
            var otherCharges = await GetOtherChargesAsync();
            var subTotalPlusOtherCharges = subTotal + otherCharges;
            var salesTax = Math.Round(subTotalPlusOtherCharges * salesTaxPercentage, 2, 
                                      MidpointRounding.AwayFromZero);

            return subTotalPlusOtherCharges + salesTax;
        }
    }
}

The MathService class has just one public static and asynchronous method, GetCalculatedTotalAsync. This method receives a sales tax percentage parameter (salesTaxPercentage) and calls two private asynchronous methods, GetSubTotalAsync and GetOtherChargesAsync. As a convention, asynchronous methods that include the async modifier, must include the Async suffix. It is highly recommended to follow the naming convention because asynchronous methods offered by .NET Framework 4.5 class use that convention. This way, whenever you see a method with the Async suffix, you know that you can use the await keyword to make the asynchronous call.

The GetCalculatedTotalAsync method declaration uses the async modifier and returns a Task<decimal>:

public static async Task<decimal>  GetCalculatedTotalAsync(decimal salesTaxPercentage)


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video