Channels ▼


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

However, if you take a look at the code for that method, you will notice there is no code to create any Task and that the return statement returns the result of a sum of two decimal variables. The code just returns a decimal but the async modifier will wrap and unwrap the decimal variable under the hoods. We don't need to think about either tasks or continuations, the code is pretty similar than synchronous code. The method represent a very common case in which we need to wait for I/O bound operations to compute a final result and return it. The method performs the following steps:

  • Call the GetSubTotalAsync method with an asynchronous execution to compute the subtotal.
  • Call the GetOtherChargesAsync method with an asynchronous execution to compute the other charges.
  • Compute the sum of the subtotal plus the other charges.
  • Calculate the sales tax amount based on the subtotal plus other charges computed in the aforementioned step.
  • Return the sum of the subtotal plus other charges plus the sales tax amount.

The code that retrieves the subtotal uses the await keyword make the call to the GetSubTotalAsync method with an asynchronous execution.

var subTotal = await GetSubTotalAsync();

The next line won't be executed until the GetSubTotalAsync method finishes its execution and the subTotal variable has the value returned from the method or an exception occurs. Thus, the code behaves just like synchronous code. I will dive deeper on exception handling later.

You can think of the GetSubTotalAsync method as the typical I/O bound operation that you don't want to block the UI until it finishes. In this case, I used the new DownloadStringTaskAsync method for the WebClient class. .NET Framework 4.5 added many methods with the Async suffix that can be called with the await modifier to the WebClient class and to other .NET classes. The code just downloads the contents of Dr Dobb's home page with an asynchronous execution and just converts the first character to a decimal value. Forgive me for the simplicity; I want to keep the example as simple as possible while providing some real-life I/O bound operations.

The GetOtherChargesAsync method does the same thing than the GetSubTotalAsync method but it takes the second character of the string instead of the first one. Again, the idea was to have two real I/O bound operations.

The following listing shows the code for MainWindow.xaml. The simple UI displays a button and a listbox on a WPF Window (see Figure 1).

<Window x:Class="WpfAsyncAwaitSample.MainWindow"
        Title="MainWindow" Height="350" Width="525">
        <Button Name="UpdateTotal" Content="Add total" HorizontalAlignment="Left" Height="66"
           Margin="10,10,0,0" VerticalAlignment="Top" Width="252" Click="UpdateTotalClick"/>
       <ListBox Name="TotalList" HorizontalAlignment="Left" Height="220" Margin="10,91,0,0"
           VerticalAlignment="Top" Width="498" />

Figure 1. The UI design with a button and a listbox. The button calls an asynchronous method and doesn't block the UI.

The following listing shows the code for MainWindow.xaml.cs, the interaction logic for MainWindow. It's very simple the UpdateTotalClick even handler calls MathService.GetCalculatedTotalAsync with an asynchronous execution and then adds the calculated total to the TotalList listbox. Notice that the event handler method declaration includes the async modifier because it uses the await keyword to execute MathService.GetCalculatedTotalAsync. To keep things simple, I didn't create a MVVM (short for Model-View-ViewModel) WPF solution.

namespace WpfAsyncAwaitSample
    using System.Windows;

    public partial class MainWindow : Window
        public MainWindow()

        private async void UpdateTotalClick(object sender, RoutedEventArgs e)
            //// Sales Tax = 8.5% = 0.0850
            const decimal salesTax = 0.0850M;
            var total = await MathService.GetCalculatedTotalAsync(salesTax);


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.