async and await c#

This article is to build a sample common async and await block.

It is a bit tricky and need to be careful when using async and await. I have copy and paste and to construct a console project for async and await sample.

Wait until the total is printed before you hit any key to quit.

class Program


    static void Main(string[] args)


        Task t = new Task(startasync);



        Console.WriteLine(“Press Enter to quit”);




    public static async void startasync()


        // One-step async call.

        await SumPageSizesAsync();


    private static async Task SumPageSizesAsync()


        // Make a list of web addresses.

        List<string> urlList = SetUpURLList();


            // Create a query.

    IEnumerable<Task<int>> downloadTasksQuery =

        from url in urlList select ProcessURLAsync(url);


    // Use ToArray to execute the query and start the download tasks.

    Task<int>[] downloadTasks = downloadTasksQuery.ToArray();


    // You can do other work here before awaiting.


    // Await the completion of all the running tasks.

    int[] lengths = await Task.WhenAll(downloadTasks);


    //// The previous line is equivalent to the following two statements.

    //Task<int[]> whenAllTask = Task.WhenAll(downloadTasks);

    //int[] lengths = await whenAllTask;


    int total = lengths.Sum();


    //var total = 0;

    total += urlContents.Length;



           string.Format(“\r\n\r\nTotal bytes returned:  {0}\r\n”, total));



    private static List<string> SetUpURLList()


        List<string> urls = new List<string>













        return urls;



    // The actions from the foreach loop are moved to this async method.

    private static async Task<int> ProcessURLAsync(string url)


        var byteArray = await GetURLContentsAsync(url);

        DisplayResults(url, byteArray);

        return byteArray.Length;



    private static async Task<byte[]> GetURLContentsAsync(string url)


        // The downloaded resource ends up in the variable named content.

        var content = new MemoryStream();


        // Initialize an HttpWebRequest for the current URL.

        var webReq = (HttpWebRequest)WebRequest.Create(url);


        // Send the request to the Internet resource and wait for

        // the response.

        Task<WebResponse> responseTask = webReq.GetResponseAsync();


        using (WebResponse response = await responseTask)


            // The following line can replace the previous two lines.

            //using (WebResponse response = await webReq.GetResponseAsync())


            // Get the data stream that is associated with the specified URL.

            using (Stream responseStream = response.GetResponseStream())


                // Read the bytes in responseStream and copy them to content.

                await responseStream.CopyToAsync(content);


                // The previous statement abbreviates the following two statements.


                // CopyToAsync returns a Task, not a Task<T>.

                //Task copyTask = responseStream.CopyToAsync(content);


                // When copyTask is completed, content contains a copy of

                // responseStream.

                //await copyTask;



        // Return the result as a byte array.

        return content.ToArray();



    private static void DisplayResults(string url, byte[] content)


        // Display the length of each website. The string format

        // is designed to be used with a monospaced font, such as

        // Lucida Console or Global Monospace.

        var bytes = content.Length;

        // Strip off the “http://&#8221;.

        var displayURL = url.Replace(http://&#8221;, “”);

        Console.WriteLine( string.Format(“\n{0,-58} {1,8}”, displayURL, bytes));



You can also download a single solution from The sample file name is My MSN ID is


About chanmingman

Since March 2011 Microsoft Live Spaces migrated to Wordpress ( till now, I have is over 1 million viewers. This blog is about more than 50% telling you how to resolve error messages, especial for Microsoft products. The blog also has a lot of guidance teaching you how to get stated certain Microsoft technologies. The blog also uses as a help to keep my memory. The blog is never meant to give people consulting services or silver bullet solutions. It is a contribution to the community. Thanks for your support over the years. Ming Man is Microsoft MVP since year 2006. He is a software development manager for a multinational company. With 25 years of experience in the IT field, he has developed system using Clipper, COBOL, VB5, VB6, VB.NET, Java and C #. He has been using Visual Studio (.NET) since the Beta back in year 2000. He and the team have developed many projects using .NET platform such as SCM, and HR based applications. He is familiar with the N-Tier design of business application and is also an expert with database experience in MS SQL, Oracle and AS 400.
This entry was posted in .Net and tagged , , . Bookmark the permalink.

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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