C# Modifier async / await

Modifier: async / await

Used to mark a method as being asynchronous and to await results from the asynchronous processing. Available from .NET 4.5 (C# 5).


using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows;

namespace Examples
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
        /// <summary>
        /// Standard WPF initialization
        /// </summary>
        public MainWindow()
            Console.WriteLine("Finished Initializing.");

        /// <summary>
        /// Async download webpage
        /// </summary>
        /// <returns></returns>
        async Task<int> DownloadWeb()
            Console.WriteLine("Started Async.");
            HttpClient client = new HttpClient();
            Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");

            Console.WriteLine("Starting await.");
            string urlContents = await getStringTask;
            Console.WriteLine("Finished await.");
            return urlContents.Length;

        /// <summary>
        /// Handle a button press as an async task
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Button_Click(object sender, RoutedEventArgs e)
            int length = await DownloadWeb();
            Console.WriteLine("Got Result: " + length);


<Window x:Class="Examples.MainWindow"
        Title="MainWindow" Height="350" Width="525">
        <Button Content="Button" HorizontalAlignment="Left" Margin="305,134,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: